链表中倒数第k个节点(栈 或者 快慢指针)

链表中倒数第k个节点

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

这里提供两种解法

法一 用栈逆序链表 返回第k个节点

法二 快慢指针

先看第一种

package com.robot;

import java.util.Stack;

public class Solution {
    public static void main(String[] args) {
            ListNode head=new ListNode(1);
            ListNode node2=new ListNode(2);
            ListNode node3=new ListNode(3);
            ListNode node4=new ListNode(4);
            ListNode node5=new ListNode(5);
            head.next=node2;
            node2.next=node3;
            node3.next=node4;
            node4.next=node5;
            node5.next=null;
            ListNode node=FindKthToTail(head,4);
            System.out.println(node.val);

    }
    public static ListNode FindKthToTail(ListNode head, int k) {
        if(head==null||k==0){
            return null;
        }
        int count=0;
        ListNode node=head;
        Stack<ListNode> stack=new Stack<>();
        while(node!=null){
            stack.push(node);
            node=node.next;
            count++;
        }
        if(count<k){
            return null;
        }
        int num=1;
        while(num<=k){
            node=stack.pop();
            num++;
        }
        return node;
    }
}
package com.robot;

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

在这里插入图片描述

法二

定义快指针和慢指针

快指针先走 k-1 步,到达第 k 个节点

然后两指针同时齐步走,当快指针到达末尾时,慢指针在倒数第 k 个节点上

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head==null||k<=0){
            return null;
        }
        ListNode fast=head;
        ListNode slow=head;
        for(int i=1;i<k;i++){
            if(fast.next==null){
                return null;
            }
            fast=fast.next;
        }
        while(fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }
}
发布了39 篇原创文章 · 获赞 19 · 访问量 1483

猜你喜欢

转载自blog.csdn.net/weixin_44222272/article/details/105095905