剑指Offer-返回倒数第k个节点

返回倒数第k个节点。LinkedList
package 剑指Offer;

import java.util.Stack;

/**
 * @program:多线程和IO
 * @descripton:返回倒数第k个节点
 * @author:ZhengCheng
 * @create:2021/10/11-14:36
 **/
public class DeleteNodeBackward {
    //题解中均未考虑k会大于链表长度的情况
    public static void main(String[] args) {
        Node<Integer> head = new Node<Integer>(1,1);
        Node node2 = new Node(2, 2);
        Node node3 = new Node(3, 3);
        Node node4 = new Node(4, 4);
        Node node5 = new Node(5, 5);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        //Node node = new DeleteNodeBackward().checkBackwardA(head, 2);
        //Node node = new DeleteNodeBackward().checkBackwardB(head,2);
        Node node = new DeleteNodeBackward().checkBackwardC(head,2);
        System.out.println(node);

    }
    //思路1:遍历一次,然后少数几个
    private Node checkBackwardA(Node head ,int k){
        Node temp = head ;
        int cnt = 1 ;
        while (temp.next != null){
            temp=temp.next;
            cnt++;
        }
        temp = head;
        for (int i = 0; i < cnt - k; i++) {
            temp = temp.next;
        }
        return temp;
    }

    //思路2:入栈,弹栈k个
    private Node checkBackwardB(Node head ,int k){
        Node temp = head;
        Stack<Node> nodes = new Stack<>();
        nodes.push(temp);
        while (temp.next != null){
            temp=temp.next;
            nodes.push(temp);
        }
        Node pop = null;
        for (int i = 0; i < k; i++) {
           pop  = nodes.pop();
        }
        return pop;
    }
    //思路3 :使用双指针,避免统计总数。当后指针指到了最后一个,那么
    //前一个指针位于n-k即可。即时时刻刻保持,两指针间相差k个。
    private Node checkBackwardC(Node head, int k){
        Node tempA = head;
        Node tempB = head;
        for (int i = 0; i < k-1; i++) {
            tempB = tempB.next;
        }
        while (tempB.next!= null){
            tempA = tempA.next;
            tempB = tempB.next;
        }
        return tempA;
    }
}
class Node<T> {
    private int id;
    private T t;
    public Node next;
    public Node(int id, T t) {
        this.id = id;
        this.t = t;
    }

    @Override
    public String toString() {
        return "Node{" +
                "id=" + id +
                ", t=" + t +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值