标签:interview
2.2 Implement an algorithm to find the nth to last element of a singly linked list.
// Assume the input list has no circle.
// O(n)
Node findNthNodeToLast(Node root, int n)
{
// Find size
Node n = root;
int size = 0;
while (n != null)
{
size ++;
n = n.next;
}
if (n > size)
return null;
int nFromTheStart = size - n;
n = root;
while (nFromTheStart != 0)
{
n = n.next;
}
n;
}Another solution is to keep 2 pointer pointing for X, and X+n.
When X+n to end, return X.
// O (n)
Node findNthNodeToLast(Node head, int n)
{
Node n = head;
for (int i = 0 ; i < n ; i ++)
{
if (n == null)
return null;
n = n.next;
}
Node toReturn = head;
while (n != null)
{
toReturn = toReturn.next;
n = n.next;
}
return toReturn;
}标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1581730