题目描述
输入一个链表,输出该链表中倒数第k个结点。
代码如下:
import java.util.Stack;
public class FindKthToTailTest {
public static class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val = val;
}
}
public static void main(String[] args) {
ListNode node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
FindKthToTail(node,0);
}
/**
* 将链表压栈, 然后k次出栈, 找到的即是倒数第k个结点
* @param head
* @param k
* @return
*/
public static ListNode FindKthToTail(ListNode head,int k) {
Stack<ListNode>stack = new Stack<>();
while(head != null){
stack.push(head);
head = head.next;
}
if(k > stack.size() || k <= 0)
return null;
int count = 1;
while(!stack.isEmpty() && count < k){
stack.pop();
count++;
}
System.out.println(stack.peek().val);
return stack.pop();
}
}