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.
Classic solution: Set a Sentinel and then the first two swaps to the last two.
PublicListNode Swappairs (ListNode head) {if(Head = =NULL)returnHead; varSentinel =NewListNode (-1); Sentinel.next=Head; vardummy =Sentinel; while(Head! =NULL&& Head.next! =NULL) {Dummy.next=Head.next; Head.next=Head.next.next; Dummy.next.next=Head; Dummy=Head; Head=Head.next; } returnSentinel.next; /*ListNode sentiential = new ListNode (0); Sentiential.next = head; ListNode p = head; ListNode d = sentiential; while (P! = null && P.next = null) {D.next = P.next; d = p; p = p.next.next; D.next.next = D; } d.next = P; return sentiential.next;*/ }
This place I made a mistake at first, which is to put the commented out line below.
PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead; varSentinel =NewListNode (-1); Sentinel.next=Head; vardummy =Sentinel; while(Head! =NULL&& Head.next! =NULL) {Sentinel.next=Head.next; //head.next = Head.next.next;Sentinel.next.next =Head; Sentinel=Head; Head.next=Head.next.next; Head=Head.next; } returnDummy.next; }
This can cause problems, head is 1.
Sentinel.next = Head.next;
= = Sentinel.next to 2
Sentinel.next.next = head;
= = 2.next = head = 1;
At this point the 1.next remains at 2. Then 1.next is 2,2.next for 1,deadlock. You need to reassign the Head.next first.
or split the list interval into two lists, and then put them together one after the other.
PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead; varSEC =Head.next; varSentinel =NewListNode (-1); vardummy =Sentinel; varHeadsentinel =Head; ListNode NextNode=NULL; ListNode Nextsnode=NULL; while(Head! =NULL&& Head.next! =NULL) {Sentinel.next=Head.next; Head.next=Head.next.next; Sentinel=Sentinel.next; Head=Head.next; } varFront =Dummy.next; varSecond =Headsentinel; while(Front! =NULL) {NextNode=Front.next; Nextsnode=Second.next; Front.next=second; Second.next=NextNode; Front=NextNode; Second=Nextsnode; } returnDummy.next; }
Swap Nodes in Pairs