链表中倒数第k个结点
题目描述
输入一个链表,输出该链表中倒数第k个结点。
直接查找
先遍历求得链表长度,再遍历查找。
时间复杂度O(n)。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode* p = pListHead;
unsigned int cnt = 0, num = 0;
while (p != NULL)
{
p = p->next;
cnt++;
}
p = pListHead;
k = cnt - k + 1;
while (p)
{
num++;
if (num == k)
{
break;
}
p = p->next;
}
return p;
}
};
双指针
求倒数第k个结点,设立两个指针p1,p2。p1先遍历,p2慢k个结点,待到p1遍历完,p2便是倒数第k个结点。
时间复杂度O(n)。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode *p1 = pListHead, *p2 = pListHead;
unsigned int step = 0;
while (p1)
{
if (step >= k)
{
p2 = p2->next;
}
p1 = p1->next;
step++;
}
return step >= k ? p2 : NULL;
}
};