problem:
Given a linked list, swap every, adjacent nodes and return its head.
For example,
Given 1->2->3->4 , you should return the list as 2->1->4->3 .
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
Analysis:
case Continue ...
Wrong solution:
Public classSolution { PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL) returnHead; ListNode Dummy=NewListNode (1); ListNode Pre=dummy; Dummy.next=Head; ListNode Node1=Head; ListNode Node2=Head.next; while(Node1! =NULL&& Node2! =NULL) {ListNode temp=Node2.next; Pre.next=Node2; Node2.next=Node1; Node1.next=temp;if(Node2.next! =NULL) {Node1=Node2.next; if(Node2.next.next! =NULL) Node2=Node2.next.next; } } returnDummy.next; }}
Mistakes:
Error CaseLast executed input:[The]mistake1: Mistake1: Forget to update the pointer of Node1 and Node2.temp=Node1;node1=Node2;node2=Temp;pre=Node2;mistake2:ifThere is not enough nodes (2 nodes) left, you should also update on Node2, to indicate the loop should over!if(Node2.next! =NULL&& Node2.next.next! =NULL) {Node1=Node2.next; Node2=Node2.next.next;} Else{ //inorder to exit the loop, no effect on node in the LinkedListNode2 =NULL;}
Solution:
Public classSolution { PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL) returnHead; ListNode Dummy=NewListNode (1); ListNode Pre=dummy; Dummy.next=Head; ListNode Node1=Head; ListNode Node2=Head.next; while(Node2! =NULL) {ListNode temp=Node2.next; Pre.next=Node2; Node2.next=Node1; Node1.next=temp; Temp=Node1; Node1=Node2; Node2=temp; Pre=Node2; if(Node2.next! =NULL&& Node2.next.next! =NULL) {Node1=Node2.next; Node2=Node2.next.next; } Else{ //inorder to exit the loop, no effect on node in the LinkedListNode2 =NULL; } } returnDummy.next; }}
[Leetcode#24] Swap Nodes in Pairs