一个单向链表,给出头结点,找出倒数第N个结点,要求O(N)的时间复杂度
ListNode NthToTail(ListNode head, int N)
{
ListNode p = head;
ListNode pre = head;
int count = 0;
int num = N;
while(p != 0)
{
p = p.next;
count++;
if(num < 1)
{
pre = pre.next;
}
num--;
}
if(count < N)
return null;
return pre;
}