输入一个链表,输出该链表中倒数第k个结点。
解法一:
if(head==
null||k<=
0)return
null;
ListNode nodePre=head;
ListNode nodeLast=head;
for(
int i=
1;i<k;i++){
if(nodePre.
next!=
null)nodePre=nodePre.
next;
else return
null;
}
while(nodePre.
next!=
null){
nodePre = nodePre.
next;
nodeLast=nodeLast.
next;
}
return nodeLast;
解法二:
public ListNode FindKthToTail(ListNode head, int k)
{
if(k<=
0)
{
return null;
}
List<ListNode>
list =
new List<ListNode>();
while (head!=
null)
{
list.Add(head);
head = head.next;
}
int count =
list.Count;
if (count >
0&&count-k>=
0)
{
return list[count - k];
}
else
{
return null;
}
}