//returns new head pointer
Node reverse(Node head)
{
//empty list
if(head == null) return;
//all other cases, including only 1 node in the list
Node current = head.next;
Node prev = head;
Node tmp = null;
head.next = null;
while(current != null)
{
tmp = current.next;
current.next = prev;
prev = current;
current = tmp;
}
return prev; //new head
}
Node reverse(Node head)
{
//empty list
if(head == null) return;
//all other cases, including only 1 node in the list
Node current = head.next;
Node prev = head;
Node tmp = null;
head.next = null;
while(current != null)
{
tmp = current.next;
current.next = prev;
prev = current;
current = tmp;
}
return prev; //new head
}
No comments:
Post a Comment