题目描述
输入一个链表,输出该链表中倒数第k个结点。
---------------------------------------------------------
思路:利用两个指针p和q,开始都指向头节点,当p向后移动k次后,q开始移动。
p移动到为空时,q所指节点即为倒数第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
if (!pListHead || k == 0)
13
return nullptr;
14
ListNode* p = pListHead;
15
ListNode* q = pListHead;
16
int num = 0;
17
while (p&&num<k){
18
++num;
19
p = p->next;
20
}
21
if (num<k)
22
return nullptr;
23
while (p){
24
q = q->next;
25
p = p->next;
26
}
27
return q;
28
29
}
30
};
您的代码已保存