本文目录
24. 两两交换链表中的节点
代码随想录:24. 两两交换链表中的节点
Leetcode:24. 两两交换链表中的节点
直接做题
自己推导,不用虚拟头结点,基本OK,但发现[1, 2, 3, 4]输出后变成了[2, 1, 3],看了代码随想录,感觉思路不一样,还是自己捣鼓了一下,发现是没有将1索引到4。最终结果如下:
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
pre = head
cur = head.next
new_head = cur
while True:
temp = cur.next
pre.next = temp
cur.next = pre
if temp and temp.next:
pre.next = temp.next # 解决1索引到4
pre = temp
cur = temp.next
else:
return new_head
看文章
时间复杂度: O(n)
空间复杂度: O(1)
虚拟结点
相当于把我的初始边界条件判断,用虚拟节点解决了。但我感觉反而比较难理解,具体见“个人注释”。
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy_head = ListNode(next=head)