zoukankan      html  css  js  c++  java
  • 剑指offer_14:链表中倒数第k个节点

    输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。

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

    1、双指针

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode getKthFromEnd(ListNode head, int k) {
            ListNode p1=head,p2=head;
            while(p2!=null&&k>0){
                p2=p2.next;
                k--;
            }
            while(p2!=null){
                p2=p2.next;
                p1=p1.next;
            }
            return p1;
        }
    }
    

    2、栈

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode getKthFromEnd(ListNode head, int k) {
            Stack<ListNode> stack=new Stack<>();
            ListNode node=head;
            while(node!=null){
                stack.push(node);
                node=node.next;
            }
            while(k>0){
                node=stack.pop();
                k--;
            }
            return node;
        }
    }
    

    3、递归

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        int size=0;
        public ListNode getKthFromEnd(ListNode head, int k) {
            if(head==null){
                return head;
            }
            ListNode node=getKthFromEnd(head.next,k);
            if(++size==k){
                return head;
            }
            return node;
        }
    }
    
  • 相关阅读:
    CF1359D Yet Another Yet Another Task
    【数据结构】fhq_treap
    AtCoder Beginner Contest 182 题解
    UVA11992 Fast Matrix Operations
    双指针例题
    python使用国内镜像库
    APP元素定位工具之——Weditor
    安卓ADB的常见命令的使用
    函数进阶之迭代器,递归
    函数基础之对象,嵌套,名称空间和作用域
  • 原文地址:https://www.cnblogs.com/xyz-1024/p/14050166.html
Copyright © 2011-2022 走看看