0

#yyds干货盘点# LeetCode程序员面试金典:返回倒数第 k 个节点

 1 year ago
source link: https://blog.51cto.com/u_13321676/5919902
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# LeetCode程序员面试金典:返回倒数第 k 个节点

精选 原创

灰太狼_cxh 2022-12-07 18:15:33 博主文章分类:leetcode ©著作权

文章标签 单向链表 两个指针 代码实现 文章分类 Java 编程语言 阅读数188

实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。

注意:本题相对原题稍作改动

输入: 1->2->3->4->5 和 k = 2

代码实现:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int kthToLast(ListNode head, int k) {
ListNode first = head;
ListNode second = head;
//第一个指针先走k步
while (k-- > 0) {
first = first.next;
}
//然后两个指针在同时前进
while (first != null) {
first = first.next;
second = second.next;
}
return second.val;
}


}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK