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;
}
结果: