Every day a leetcode
解法1:双指针法
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int kthToLast(struct ListNode* head, int k){
struct ListNode* first=head;
struct ListNode* second=head;
while(k--) first=first->next;
while(first)
{
first=first->next;
second=second->next;
}
return second->val;
}
结果:

解法2:递归

设置一个计数器count,递归触底后,反弹,++count=k时打印当前结点的值。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int count;
int kthToLast(struct ListNode* head, int k){
if(head == NULL)
{
count=1;
return 0;
}
int ans=kthToLast(head->next,k);
if(count++ == k) return head->val;
return ans;
}
结果:

双指针与递归解法:链表中找到倒数第k个节点
这篇博客介绍了两种方法来解决链表问题,即如何找到链表中倒数第k个节点。第一种方法是使用双指针,通过同步移动两个指针直到第一个指针到达链表尾部,然后第二个指针所指向的节点就是目标节点。第二种方法则是采用递归,通过递归遍历链表并在触底后反弹,当计数器等于k时返回当前节点的值。这两种方法都有效地解决了链表问题。
228

被折叠的 条评论
为什么被折叠?



