返回倒数第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; } }