• 链表中倒数第k个节点


    输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。

    例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 k = 2.

    返回链表 4->5.

    方法一:两次遍历

    class ListNode {
        int val;
        ListNode next;
    
        ListNode(int x) {
            val = x;
        }
    }
    
    
    public class Solution {
    
        public static void main(String[] args) {
            ListNode head = new ListNode(2);
            Solution solution = new Solution();
            ListNode kthFromEnd = solution.getKthFromEnd(head, 1);
            System.out.println(kthFromEnd.val);
        }
    
    
        public ListNode getKthFromEnd(ListNode head, int k) {
            int Len = 0;
            ListNode point = head;
            while (point != null) {
                Len += 1;
                point = point.next;
            }
            point = head;
            System.out.println("Len:" + Len);
            for (int i = 0; i < Len - k; i++) {
                point = point.next;
            }
            return point;
        }
    
    }

    方法二:双指针法

    class ListNode {
        int val;
        ListNode next;
    
        ListNode(int x) {
            val = x;
        }
    }
    
    
    public class Solution {
    
        public static void main(String[] args) {
            ListNode head = new ListNode(2);
            Solution solution = new Solution();
            ListNode kthFromEnd = solution.getKthFromEnd(head, 1);
            System.out.println(kthFromEnd.val);
        }
    
    public ListNode getKthFromEnd(ListNode head, int k) {
            ListNode start = head, end = head;
            for (int i = 0; i < k; i++) {
                end = end.next;
            }
            while (end != null) {
                end = end.next;
                start = start.next;
            }
            return start;
        }
    
    
    }
  • 相关阅读:
    shell脚本批量启动jar
    springboot最简单的AOP
    springboot 将null字段输出为空串
    随便记录
    MySQL case when 用法
    JavaDate数据返回到前端变数字的问题
    多级菜单无限递归
    linux tomacat 之部署 war包
    linux tomcat部署 之 jre
    leetcode Best Time to Buy and Sell Stock
  • 原文地址:https://www.cnblogs.com/iuyy/p/13687113.html
Copyright © 2020-2023  润新知