版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zj15527620802/article/details/83279242
package JZoffertest;
import JZoffertest.test3.ListNode;
public class test14a {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<=0) {
return null;
}
ListNode pre=head;
ListNode last=head;
for(int i=1;i<k;i++) {
if(pre.next!=null)
pre=pre.next;
else {
return null;
}
}
while(pre.next!=null) {
pre=pre.next;
last=last.next;
}
return last;
}
}
package JZoffertest;
import java.util.Stack;
import JZoffertest.test3.ListNode;
public class test14 {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<=0) {
return null;
}
//先将链表翻转,再打印第k个
Stack<ListNode> stack=new Stack<ListNode>();
int count=0;
while(head!=null) {
stack.push(head);
head=head.next;
count++;
}
if(count<k) {
return null;
}
ListNode knode=null;
for(int i=0;i<k;i++) {
knode=stack.pop();
}
return knode;
}
}