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;
        }
    }
    
  • 相关阅读:
    C和C++的不同点
    音频质量评价指标
    常用函数整理
    Subband Decomposition
    Stability Analysis of Algorithms
    Time Frequency (T-F) Masking Technique
    雅克比(Jacobi)方法
    寒假3
    寒假作业二
    寒假 2
  • 原文地址:https://www.cnblogs.com/xyz-1024/p/14050166.html
Copyright © 2011-2022 走看看