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.
Iterative vestion:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode Swappairs (ListNode head) { One if(Head = =NULL|| Head.next = =NULL) { A returnhead; - } -ListNode dummy =NewListNode (0); theDummy.next =head; -Head =dummy; - while(Head.next! =NULL&& Head.next.next! =NULL) { -ListNode N1 =Head.next; +ListNode N2 =Head.next.next; -N1.next =N2.next; +Head.next =N2; AN2.next =N1; atHead =N1; - } - returnDummy.next; - - } -}
Recursive Version
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode Swappairs (ListNode head) { One if(Head = =NULL|| Head.next = =NULL) { A returnhead; - } -ListNode tail =Swappairs (head.next.next); theListNode temp =Head.next; -Head.next =tail; -Temp.next =head; - returntemp; + - } +}
Swap Nodes in Pairs