Amazon Interview Question
Java DevelopersCountry: United States
I can't find any issue from original code if the linked list does not contains any loop.
Problems are :
1. As mentioned by Dinesh,
2. No iterator used to iterate through linkedlist
public static LinkedList<Integer> reverse(LinkedList<Integer> current)
{
LinkedList<Integer> result = new LinkedList<Integer>();
if (current == null) {
return null;
}
Iterator<Integer> li = current.iterator();
while (li.hasNext()) {
int next = li.next();
result.addFirst(next);
}
return result;
}
the code is always loosing the head element in the iteration
Suppose we have following list
a -> b -> c -> d
So the reverse would be like this
d-> c-> b
public void reverse()
{
Node<E> temp=head;
head=tail; // //swap head and tail
tail=temp; //tail points to head
//traverse the list swapping prev and next fields of each node
Node<E> p=head; //create a node and point to head
while(p!=null) //while p does not equal null
{ //swap prev and next of current node
temp=p.next;
p.next=p.prev; //point next pointer to previous
p.prev=temp; //previous point to what next used to point to
p=p.next;//advance current node
}
}
Find the issue with the above code and fix it.
- Jackie December 05, 2013