9.2チェーンテーブル(二)――一方向チェーンテーブルの最後からk番目のノードを探し出す


/**
*機能:一方向チェーンテーブルの最後からk番目のノードを見つけます.
 */
3つの方法:
1、方法一:
      /*        ,        ,        0    ,                1.
          =k ,     k   。*/
      //      :      k     ,             。
      public static int nthToLast(LinkedListNode head, int k){
             if( head== null)
                   return 0;
             int i= nthToLast(head.next,k)+1;
             if( i== k)
                  System. out.println( head. data);
             return i;
      }

2、
方法2:
      //     :       (        )       ,         。
      public static LinkedListNode nthToLast2(LinkedListNode head, int k,IntWrapper i){
             if( head== null)
                   return null;
            LinkedListNode node= nthToLast2(head.next,k,i);
             i. value++;
             if( i. value== k){
                   return head;
            }
             return node;
      }
      /*
       *        ,      public class  。     public static class main。
       *  Java ,                 。              ,                        。
       *              ,          public class  public static class。
       */    
      public static class IntWrapper{
             public int value=0;
      }

3、方法3:
      /**
       *       p1 p2,          K        。
       *     :        , p1    k   。         , p1        ,p2
       *      k   。
       * @param head
       * @param k
       * @return
       */
      public static LinkedListNode nthToLast3(LinkedListNode head, int k){
             if( head== null)
                   return null;
            
            LinkedListNode p1= head;
            LinkedListNode p2= head;
             for( int i=0; i< k; i++){
                   if( p1== null)       //   ,      
                         return null;
                   p1= p1. next;
            }
             if( p1== null)       //   , p1   k    ,      
                   return null;
             while( p1!= null){
                   p1= p1. next;
                   p2= p2. next;
            }
             return p2;
      }