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 { 13 if (k <= 0||!pListHead) return NULL; 14 ListNode* p1 = pListHead; 15 ListNode* p2 = pListHead; 16 //p1向前移动到第k个节点,即移动k-1次 17 for (int i = 1;i < k;i++) 18 { 19 p1 = p1->next; 20 if (p1 == NULL) 21 return NULL; 22 } 23 //当p1移动到最后一个节点的时候,p2正好移动到倒数第k个节点 24 while (p1->next != NULL) 25 { 26 p1 = p1->next; 27 p2 = p2->next; 28 } 29 return p2; 30 } 31 };
转载于:https://www.cnblogs.com/hslzju/p/5707618.html