实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
来源:力扣(LeetCode)
暴力遍历
第一次遍历记录链表元素个数
第二次查找所在位置
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int
kthToLast(struct ListNode* head, int k)
{
if (head == NULL)
{
return -1;
}
else if(head -> next == NULL)
{
return head -> val;
}
struct ListNode *cur = head;
int cnt = 0;
while (cur)
{
cur = cur -> next;
cnt ++;
}
int end = cnt - k;
int ans = 0;
if (end == 0)
{
return head -> val;
}
cur = head;
cnt = 0;
while (cur)
{
cur = cur -> next;
cnt ++;
if (cnt == end)
{
ans = cur -> val;
}
}
return ans;
}