首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【LeetCode程序员面试金典】面试题 02.02. Kth Node From End of List LCCI

【LeetCode程序员面试金典】面试题 02.02. Kth Node From End of List LCCI

作者头像
韩旭051
发布2020-06-23 10:45:08
发布2020-06-23 10:45:08
3910
举报
文章被收录于专栏:刷题笔记刷题笔记

Implement an algorithm to find the kth to last element of a singly linked list. Return the value of the element.

Note: This problem is slightly different from the original one in the book.

Example:

Input: 1->2->3->4->5 和 k = 2 Output: 4 Note:

k is always valid.

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

超级典型快慢指针 简单题

代码语言:javascript
复制
/**
 * 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, second = head;
        for(int i=0;i<k;i++){
            first=first.next;
        }
        while(first!=null){
            first = first.next;
            second = second.next;
        }
        return second.val;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 超级典型快慢指针 简单题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档