Skip to main content

Swap Nodes in Pairs

描述​

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.

分析​

无

代码​

# Swap Nodes in Pairs
# 时间复杂度O(n),空间复杂度O(1)
class Solution:
def swapPairs(self, head):
if head is None or head.next is None: return head
dummy = ListNode(-1, head)

prev = dummy
cur = prev.next
next = cur.next
while next:
prev.next = next
cur.next = next.next
next.next = cur

prev = cur
cur = cur.next
next = cur.next if cur else None
return dummy.next

下面这种写法更简洁,但题目规定了不准这样做。


// Swap Nodes in Pairs
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p = head;

while (p != null && p.next != null) {
int tmp = p.val;
p.val = p.next.val;
p.next.val = tmp;

p = p.next.next;
}

return head;
}
}

相关题目​