题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路1:
先对链表遍历,得到链表的长度。再从表头开始遍历n-k步。
/*
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(pListHead == NULL || k==0) return NULL;
int n=0;
ListNode * cur = pListHead;
while(cur)
{
n++;
cur = cur->next;
}
if(n<k) return NULL;
cur = pListHead;
for(int i=0; i<n-k; i++)
cur = cur->next;
return cur;
}
};
思路2 (fast-low思想):
建立两个指针均指向表头,第一个fast先走k-1步,然后两个指针同时移动,当fast指针指向链尾时停止,返回low指针。
/*
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(pListHead == NULL || k==0) return NULL;
ListNode * cur1 = pListHead;
ListNode * cur2 = pListHead;
for(int i=0; i<k-1; i++)
{
if(cur1->next ==NULL) return NULL;
else cur1 = cur1->next;
}
while(cur1->next)
{
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur2;
}
};