Given a linked list, swap every two 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. You may not modify the values in the list, only nodes itself can be changed.
Analysis:
Could use recursion or iterative
Java
public ListNode swapPairs(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode helper = new ListNode(0);
helper.next = head;
ListNode n1 = helper;
ListNode n2 = head;
while(n2!=null && n2.next!=null){
ListNode temp = n2.next.next;
n2.next.next = n1.next;
n1.next = n2.next;
n2.next = temp;
n1 = n2;
n2 = n1.next;
}
return helper.next;
}
another
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode p1 = newHead;
int len = 0;
ListNode l1 = head;
while(l1!=null){
l1 = l1.next;
len++;
}
int dis = len/2;
l1 = head;
while(dis>0){
ListNode l2 = l1.next;
l1.next = l2.next;
l2.next = l1;
p1.next = l2;
p1 = l1;
l1 = l1.next;
dis--;
}
return newHead.next;
}
c++
recursion
ListNode *swapPairs(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *newPair = head->next->next;
ListNode *newHead = head->next;
head->next->next = head;
head->next = swapPairs(newPair);
return newHead;
}