题目链接
https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
题目
实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
注意:本题相对原题稍作改动
示例
输入: 1->2->3->4->5 和 k = 2 输出: 4
说明
给定的 k 保证是有效的。
思路
本题和Leetcode-剑指 Offer 22: 链表中倒数第k个节点几乎一模一样,可参考该题思路。
C++ Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int kthToLast(ListNode* head, int k) {
int n=0;
ListNode* cur=head;
while(cur!=NULL)
{
n++; cur=cur->next;
}
cur=head;
int i=0;
if(n-k-1>=0)
{
while(i!=n-k)
{
cur=cur->next; i++;
}
}
return cur->val;
}
};