/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
int number=0;
if(head==null)//判断首节点是否为空
{
return null;
}
//存储值域的栈
Stack<Integer> value=new Stack<Integer>();
//存储指针域的栈
Stack<ListNode> point=new Stack<ListNode>();
ListNode finalNode=head;
ListNode newNode=head;
while(head!=null&&newNode!=null)
{
value.push(newNode.val);
point.push(newNode.next);
newNode=newNode.next;
//计数链表长度
number+=1;
}
//k超过链表长度或为非正数,返回null
if(k>number||k<=0)
{
return null;
}
for(int i=0;i<k;i++)
{
if(i==k-1)
{
finalNode.val=value.pop();
finalNode.next=point.pop();
}else{
value.pop();
point.pop();
}
}
return finalNode;
}
}
//比较刚硬的结题思路,并没有考虑到复杂度,因为返回的是倒数的第k个节点,利用栈的后进先出的特性,构造出一个符合要求的数据结构,相比直接遍历和构造两个链表节点,并且设置游标让快的领先慢的k个的思路来说,更容易理解,仅做题目理解方法,不做推荐