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
分析
-
Time complexity: O(n)O(n)O(n)
-
Space complexity: O(1)O(1)O(1)
相关文章推荐
- 100天精刷LeetCode-Day5:141 Linked List Cycle问题(附详细思路和python题解)
- leetcode 题解 || Swap Nodes in Pairs 问题
- leetcode 题解 || Swap Nodes in Pairs 问题
- [LeetCode]题解(python):024-Swap Nodes in Pairs
- 100天精刷LeetCode-Day4:Reverse Linked List问题(附详细思路和python题解)
- 100天精刷LeetCode-Day6:Linked List Cycle2问题(附详细思路和python题解)
- Swap Nodes in Pairs Leetcode Python
- leetcode 【 Swap Nodes in Pairs 】python 实现
- leetcode Swap Nodes in Pairs python
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- LeetCode题解:Swap Nodes in Pairs
- leetcode题解-24. Swap Nodes in Pairs
- python写算法题:leetcode: 24. Swap Nodes in Pairs
- [leetcode]Swap Nodes in Pairs @ Python
- LeetCode题解:Swap Nodes in Pairs
- LeetCode :: Swap Nodes in Pairs [详细分析]
- 24. Swap Nodes in Pairs Leetcode Python
- [leetcode: Python]24. Swap Nodes in Pairs
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- [Leetcode][Python]24: Swap Nodes in Pairs