思路一:
两个指针,先让第一个指针和第二个指针都指向头结点,然后再让第一个指正走(k-1)步,到达第k个节点。然后两个指针同时往后移动,当第一个结点到达末尾的时候,第二个结点所在位置就是倒数第k个节点了。
/*
public class ListNode
{
int val;
ListNode next = null;
ListNode(int val)
{
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<=0) return null;
ListNode l1=head, l2=head;
for(int i=1; i<=k-1; i++)
{
if(l1.next!=null) l1=l1.next;
else return null;
}
while(l1.next!=null)
{
l1=l1.next;
l2=l2.next;
}
return l2;
}
}
public class Solution{
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<=0) return null;
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 kthNode=null;
for(int i=0; i<k; i++)
kthNode=stack.pop();
return kthNode;
}
}