1. 程式人生 > >12,求鏈表的倒數第k個節點《劍指offer》

12,求鏈表的倒數第k個節點《劍指offer》

signed cnblogs for brush strong 節點 highlight pre 輸入

題目:

輸入一個鏈表,輸出該鏈表中倒數第k個結點。

思路:

兩個指針一個先走k步,然後兩個一起走,先走的到達終點時後一個指向的就是所求的節點,註意可能長度小於k,這時候應該返回null

代碼:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
       if(pListHead==NULL||k==0) return NULL;
       int i;
       ListNode* p1=pListHead;
       ListNode* p2=pListHead;
       for(i=0;i<k-1;i++){
           if(p1->next!=NULL){
             p1=p1->next;
           }else{
               return NULL;
           }
       
       }
      while(p1->next!=NULL){
          p1=p1->next;
          p2=p2->next;
      }
       return p2;
    }
};

  

12,求鏈表的倒數第k個節點《劍指offer》