难度: Medium
原题连接
内容描述
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.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******
一眼就知道这个用递归做,beats 100%
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
tmp = head.next
head.next = self.swapPairs(head.next.next)
tmp.next = head
return tmp
思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******
或者用loop
做,每个node
关系要弄清楚, 又是巧用dummy
,dummy
大法对于nodeList
的题目简直无敌!!!🐂批, 但是只beats
了69.40%
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
cur = dummy = ListNode(-1)
dummy.next = head
while cur.next and cur.next.next:
next_one, next_two, next_three = cur.next, cur.next.next, cur.next.next.next
cur.next = next_two
next_two.next = next_one
next_one.next = next_three
cur = next_one
return dummy.next