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.
给定一个链表,每两个节点为一组交换位置。只使用常量空间,不能修改链表的值,只能修改链表的指针。
题目本身不难,但要操作很多指针,容易弄错。
解法1: 迭代。新建一个dummy节点,使用三个节点指针。
解法2: 递归
Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode swapPairs(ListNode head) {
if (head == null) {
return null;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode r = dummyHead;
while (r != null && r.next != null && r.next.next != null) {
ListNode p = r.next.next;
ListNode q = r.next;
ListNode next = p.next;
p.next = q;
q.next = next;
r.next = p;
p = q.next == null ? null : q.next.next;
q = q.next;
r = r.next.next;
}
return dummyHead.next;
}
}
Python: Iteration
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next and current.next.next:
next_one, next_two, next_three = current.next, current.next.next, current.next.next.next
current.next = next_two
next_two.next = next_one
next_one.next = next_three
current = next_one
return dummy.next
C++: Iteration
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummy = new ListNode(-1), *pre = dummy;
dummy->next = head;
while (pre->next && pre->next->next) {
ListNode *t = pre->next->next;
pre->next->next = t->next;
t->next = pre->next;
pre->next = t;
pre = t->next;
}
return dummy->next;
}
};
C++: Recursion
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *t = head->next;
head->next = swapPairs(head->next->next);
t->next = head;
return t;
}
};