import org.omg.CORBA.NO_IMPLEMENT;
import java.util.Stack;
/**
* 面试题22:链表中的倒数第K个节点
* 题目:输入一个链表,输出该链表中倒数第k个结点。
* 输入:{1,2,3,4,5},1
* 输出:{5}
* @author
* @create 2021-03-23 10:38
*/
public class Solution22 {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
Node res = findKthToTailSecond(node1,2);
System.out.println(res);
}
/**
* 方法一:栈,时间复杂度O(n),空间复杂度O(n)
* @param pHead
* @param k
* @return
*/
public static Node findKthToTail(Node pHead, int k){
if (pHead == null || k < 1){
return null;
}
Stack<Node> stack = new Stack<>();
Node head = pHead;
Node res = null;
while (head != null){
stack.push(head);
head = head.next;
}
int size = stack.size();
if (k > size){
return null;
}
for (int i = 0 ; i< size;i++){
if (i == k - 1){
res = stack.pop();
// res.next = null;
break;
}
stack.pop();
}
return res;
}
/**
* 方法二:快慢指针,时间复杂度O(n),空间复杂度O(1)
* @param pHead
* @param k
* @return
*/
public static Node findKthToTailSecond(Node pHead, int k){
if (pHead == null || k < 1){
return null;
}
Node fast = pHead;
for (int i = 0; i<k;i++){
if (fast != null){
fast = fast.next;
}else {
return null;
}
}
Node slow = pHead;
while (fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
class Node{
int val;
Node next = null;
public Node(int val){
this.val = val;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
", next=" + next +
'}';
}
}
【剑指Offer】面试题22:链表中倒数第k个节点
最新推荐文章于 2024-03-01 20:15:20 发布