输入一个链表,输出该链表中倒数第k个结点。
思路分析:
第一种方法:先遍历链表,统计节点数目;然后,判断总数目减去k是否大于等于0,如果大于等于0,则遍历到总数目减去k;反之,返回null。
第二种方法:设置两个指针,第一个指针先移动到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;
int count=0;
ListNode temp=head;
while(head!=null)//统计节点的个数
{
count++;
head=head.next;
}
count-=k;
head=temp;
//判断节点是否在范围内,若在范围内,则返回节点;反之,返回null
if(count>=0)
{
while(count--!=0)
{
head=head.next;
}
return head;
}
else
return null;
}
}
法二:
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k<0)
return null;
ListNode first=head;
ListNode second=head;
for(int i=0;i<k;i++)
{
if(first==null)
return null;
first=first.next;
}
while(first!=null)
{
first=first.next;
second=second.next;
}
return second;
}
}