当前位置:   article > 正文

Leetcode每日一题:面试题02.02.kth-node-from-end-of-list-lcci(返回倒数第k个节点)_leetcode每日一题:面试题02.02.kth-node-from-end-of-list-lc

leetcode每日一题:面试题02.02.kth-node-from-end-of-list-lcci(返回倒数第k个节

在这里插入图片描述
思路:典型得快慢指针问题,快指针与慢指针中间隔着k-2个节点,那么同时++快慢指针,当快指针指向链表结尾节点时,慢指针指向倒数第k个节点;
在这里插入图片描述

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

int kthToLast(ListNode *head, int k)
{
	ListNode *left = head, *right = head;
	int count = 1;
	while (count < k)
	{
		right = right->next;
		count++;
	}
	while (right->next)
	{
		left = left->next;
		right = right->next;
	}
	return left->val;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/758786
推荐阅读
相关标签
  

闽ICP备14008679号