14.链表中倒数第k个节点
题目描述
输入一个链表,输出该链表中倒数第k个结点。
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 ListNode *pre , *back;//双指针back比pre快k个节点 13 pre = pListHead; 14 back = pListHead; 15 int i = 1; 16 for(; i <= k && back!=NULL; ++i){ 17 back = back->next; 18 } 19 if(i < k + 1) return NULL;//小于k个节点 20 while(back != NULL){ 21 pre = pre->next; 22 back = back->next; 23 } 24 return pre; 25 } 26 };