2.代码输入一个长度为 n 的链表,设链表中的元素的值为 ai ,返回该链表中倒数第k个节点。如果该链表长度小于k,请返回一个长度为 0 的链表。
public class Test {
public static class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
public static ListNode FindKthToTail(ListNode pHead, int k) {
// write code here
Stack stack = new Stack<>();
int t = 0;
while(pHead!=null){
stack.push(pHead);
pHead = pHead.next;
t +=1;
}
if (k>t){
return null;
}
ListNode node = stack.pop();
for (int i = 0; i < k-1; i++) {
ListNode node1 = stack.pop();
node1.next = node;
node = node1;
System.out.println(node.val);
if (i==k-2){
return node;
}
}
return null;
}
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
FindKthToTail(n1,2);
}
}



