Swap Nodes in Pairs

Question

Problem Statement

Given a linked list, swap every two adjacent nodes and return its head.

Example

Given 1->2->3->4, you should return the list as 2->1->4->3.

Challenge

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题解1 - Iteration

1. 保存2.next
2. 2.next赋值为1
3. 1.next赋值为1中保存的2.next
4. 将前一个链表节点的 next 指向1
5. 更新前一个链表节点为1
6. 更新当前的链表节点为1中保存的2.next

Java

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode prev = dummy, curr = head;

while (curr != null && curr.next != null) {
ListNode after = curr.next;
ListNode nextCurr = after.next;
after.next = curr;
curr.next = nextCurr;
// link new node after prev
prev.next = after;
// update prev and curr
prev = curr;
curr = nextCurr;
}

return dummy.next;
}
}


题解2 - Recursion

Java

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;

ListNode after = head.next;

return after;
}
}