Input a linked list and output the k-th node from the bottom of the linked list.
p1 takes k-1 steps first, then p1 and p2 go together
C++:
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { 12 if (pListHead == NULL || k == 0) 13 return NULL ; 14 ListNode* p1 = pListHead ; 15 ListNode* p2 = pListHead ; 16 for(unsigned int i = 0 ; i < k-1 ; i++){ 17 if (p1->next != NULL){ 18 p1 = p1->next ; 19 }else{ 20 return NULL ; 21 } 22 } 23 while(p1->next != NULL){ 24 p1 = p1->next ; 25 p2 = p2->next ; 26 } 27 return p2 ; 28 } 29 };