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.
是 http://www.jianshu.com/p/6b64490cac79 的简单版本when k =2
Solution1:Recursive: 先序处理
思路:发现pattern子问题,处理好当前的,递归剩下的
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution2:Iterative
思路:遍历每次处理一个section(两个nodes)
Time Complexity: O(N) Space Complexity: O(1)
Solution2.2 Round1:Iterative
Solution1 Code:
class Solution1 {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode second = head.next;
head.next = swapPairs(second.next);
second.next = head;
return second;
}
}
Solution2 Code:
class Solution2 {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
second.next = first;
current.next = second;
current = current.next.next;
}
return dummy.next;
}
}
Solution2.2 Round1 Code:
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while(cur != null) {
cur = swapPair(cur);
}
return dummy.next;
}
private ListNode swapPair(ListNode pre) {
if(pre.next == null || pre.next.next == null) {
return null;
}
ListNode cur = pre.next;
ListNode post = cur.next;
ListNode save = post.next;
pre.next = post;
post.next = cur;
cur.next = save;
return cur;
}
}