题目:
24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
思路
链表题依然要注意使用dummy,用dummy.next指向原始的开始。
用head来进行交换,在head.next和head.next.next都存在的时候,先用虚拟的n1,n2调整好指针关系,再赋值给head.next和head。这里注意,在第一个while循环中head其实是dummy因为head = dummy是同一个对象,所以head.next=n2改变了之前dummy.next = head的关系所以不会报错。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
dummy = ListNode(0)
dummy.next = head
head = dummy
while head.next and head.next.next:
n1, n2 = head.next, head.next.next
n1.next = n2.next
n2.next = n1
head.next = n2
head = n1
return dummy.next
分析
-
Time complexity: O ( n ) O(n) O(n)
-
Space complexity: O ( 1 ) O(1) O(1)