您的位置:首页 > Web前端 > Node.js

100天精刷LeetCode-Day3:Swap Nodes in Pairs问题(附详细思路和python题解)

2020-08-26 00:15 1026 查看

题目:

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

分析

  1. Time complexity: O(n)O(n)O(n)

  2. Space complexity: O(1)O(1)O(1)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: