题目描述:
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。
题解1:(快慢指针)
1.定义两个指针,快指针 fast, 慢指针 low .
2.让 fast先向前移动 k个位置,然后 low 和 fast 再一起向前移动 .
3.当 fast 到达链表尾部,返回 low .
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
if(head==NULL)
return NULL;
ListNode* fast=head;
ListNode* low=head;
for(int i=1;i<k;i++)
{
fast=fast->next;
}
while(fast->next!=NULL)
{
fast=fast->next;
low=low->next;
}
return low;
}
};
题解2(递归):
1.先一直递归到链表尾部,再返回;
2.定义位置变量 pos ,每次函数返回时 pos++;
3.当 pos == k时,说明此时递归函数位于第 k 个结点位置,返回该结点;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int pos=0;
ListNode* getKthFromEnd(ListNode* head, int k) {
if(head==NULL)
return NULL;
ListNode* temp=getKthFromEnd(head->next,k);
pos++;
if(pos==k)
return head;///注意
return temp;///注意
}
};