The Google phone interview:
Reverse a linked list. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL,
return 5->4->3->2->1->NULL.
Check the coding in detail below
/*
Key to solve: Dummy node
Swap between curr and next node,
=> connect with dummy node
Treat prevDummy as "temporary variable"
*/
public static ListNode reverseLL(ListNode head){
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode prevDummy=dummy;
ListNode curr=head;
ListNode nextNode=head.next;
while(nextNode!=null){
//swap begin
curr.next=nextNode.next;
nextNode.next=prevDummy.next;
prevDummy.next=nextNode;
//swap completed
nextNode=curr.next;
}
return dummy.next;
}