找出鏈表中倒數第k個節點

實現這個算法,能夠用遞歸和非遞歸。由於單向鏈表只能向後遍歷,因此通常會想到用遞歸這種方法,而後當遞歸遍歷到鏈表末端時,該方法會回傳一個置爲0的計數器。node

以後的每一次調用都會將這個計數器加1,當計數器等於K時,表示咱們訪問的是鏈表倒數第K個元素。算法

方法Athis

  1. public static int nToLast(LinkedListNode head,int k){  
  2.     if(head==null){  
  3.         return 0;  
  4.     }  
  5.     int i = nToLast(head.next,k)+1;//當遍歷到最後一個元素時,計數器i開始自增。
  6.     if(i==k){  
  7.         System.out.println(head.data);  
  8.     }  
  9.     return i;  
  10. }  

可是這個方法只能打印倒數第K個值,不能返回該元素,由於咱們沒法用通常的返回語句回傳一個結點和一個計數器。指針

 

用一個簡單的類包裝計數器值,就能夠模仿按引用傳值。遞歸

  1. public class MyCount  
  2. {  
  3.     public int value = 0;     
  4. }  
  5. LinkedListNode nToLast(LinkedListNode head,int k,MyCount i){  
  6.     LinkedListNode node = nToList(head.next,k,i);  
  7.     i.value = i.value+1;  
  8.     if(i.value == k){  
  9.         return head;  
  10.     }  
  11.     return node;  
  12. }  

迭代法,一個更直接的方法,咱們能夠使用兩個指針p1和p2,並將他們指向鏈表中相距k個結點的兩個結點,具體作法是將p1和p2指向鏈表首結點,而後將 p2向後移動k個結點,以後,咱們以相同的速度移動這兩個指針,p2會在移動length-k步後抵達鏈表末尾結點,這時,p1就指向鏈表倒數第k個結 點。ast

  1. LinkedListNode nToList(LinkedListNode head,int k){  
  2.     if(k<=0)  
  3.         return null;  
  4.     LinkedListNode p1 = head;  
  5.     LinkedListNode p2 = head;  
  6.   
  7.     for(int i=0;i<k-1;i++){  
  8.         if(p2==null)   
  9.             return null;  
  10.         p2 = p2.next;  
  11.     }  
  12.     if(p2==null)  
  13.         return null;  
  14.     while(p2.next!=null){  
  15.         p1 = p1.next;  
  16.         p2 = p2.next;  
  17.     }  
  18.     return p1;  
  19. }  

 

或者class

  1. class Node{  
  2.    Node(int value, Node nnode){  
  3.       this.value=value;  
  4.       this.nnode=nnode;  
  5.    }  
  6. }  
  1. public static Node findknode(Node head, int k){  
  2.   if ((Null==head) || (Null==head.nnode))  
  3.       return head;  
  4.   cur=head;  
  5.   knode=head;  
  6.   nextnode=Null;  
  7.   count=0;  
  8.   while(cur!=Null){  
  9.      count+=1;  
  10.      if(count>=k){  
  11.          nextnode=knode.nnode;  
  12.          knode=nextnode;  
  13.       }  
  14.      nextnode=cur.nnode;  
  15.      cur=nextnode;  
  16.   }  
  17.   return knode;  
  18. }  
相關文章
相關標籤/搜索