zoukankan      html  css  js  c++  java
  • 剑指Offer编程题(Java实现)——链表中倒数第k个结点

    题目描述

    输入一个链表,输出该链表中倒数第k个结点。

    注意:

    该题目不可以用先反转链表再输出第k个结点的方式,因为反转链表会改变该结点的next指向

    思路一

    使用栈Stack倒序存储,顺序pop第k个结点

    实现

    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    import java.util.Stack;
    public class Solution {
        public ListNode FindKthToTail(ListNode head,int k) {
            // Stack
            Stack<ListNode> stack = new Stack<>();
            if(head == null) return null;
            int count = 0;
            while(head != null){
                stack.add(head);
                head = head.next;
                count++;
            }
            ListNode res = null;
            if(count < k) return res;
            for(; k > 0; k--){
                res = stack.pop();
            }
            return res;
        }
    }

    思路二

    设链表的长度为 N,寻找第n-k个节点即为第k个结点

    设置两个指针 P1 和 P2,先让 P1 移动 K 个节点,则还有 N - K 个节点可以移动。此时让 P1 和 P2 同时移动,可以知道当 P1 移动到链表结尾时,P2 移动到第 N - K 个节点处,该位置就是倒数第 K 个节点。

    实现

    public class Solution {
        public ListNode FindKthToTail(ListNode head,int k) {
            // 找到第n-k个节点
            if(head == null) return null;
            ListNode res = head;    // res为第n-k个
            while(head != null && k-->0){
                head = head.next;
            }
            if(k >0) return null;
            while(head != null){
                res = res.next;
                head = head.next;
            }
            return res;
        }
    }

     思路参考:https://www.nowcoder.com/discuss/198840

  • 相关阅读:
    ubuntu 读取群晖 nas 盘
    nginx 下载 apk、ipa 不改名zip 设置
    centos 更新时间
    go 交叉编译跨平台
    ffmpeg安装
    批量打开文件夹下所有的指定文件(批处理)
    端口流量统计
    关于 bind 和 dns
    关于使用 certbot 给网站增加 ssl
    Macos下制作可启动的u盘(转)
  • 原文地址:https://www.cnblogs.com/MWCloud/p/11323067.html
Copyright © 2011-2022 走看看