import org.omg.CORBA.NO_IMPLEMENT;
import java.util.Stack;
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);
}
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();
break;
}
stack.pop();
}
return res;
}
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 +
'}';
}
}