利用两个间隔为k的指针来实现倒数第k个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/* 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 (NULL==pListHead ||0==k)
return NULL;
ListNode * p1=pListHead;
ListNode * p2=pListHead;
for ( int i=0;i<k-1;i++)
{
if (NULL==p2->next)
return NULL;
else
p2=p2->next;
}
while (NULL!=p2->next)
{
p1=p1->next;
p2=p2->next;
}
return p1;
}
}; |