链表中倒数第k个结点

Desicription

输入一个链表,输出该链表中倒数第k个结点。

Solution

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
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
int count = 0;
ListNode* currentNode= pListHead;
while(currentNode) {
count++;
currentNode = currentNode->next;
}
count -= k;
currentNode = pListHead;
while(currentNode) {
if(!count) {
return currentNode;
}
count--;
currentNode = currentNode->next;
}
return nullptr;
}
};