当前位置: 代码迷 >> 综合 >> 每天一道leetecode:24、两两交换链表中的节点(medium)
  详细解决方案

每天一道leetecode:24、两两交换链表中的节点(medium)

热度:43   发布时间:2023-12-14 15:03:08.0

emmmmmm    22题括号生成,想了想思路,感觉如果用别的语言特别容易就写出来了,但是用python的话,emmm,暂时有点不想写,哈哈哈,罢了,改日再做,略过略过。。。

这道题很简单啊,10分钟也没用,一次就ac了。

就是简单的节点交换而已。

# Definition for singly-linked list.
class ListNode:def __init__(self, x):self.val = xself.next = Nonedef swapPairs(head):if head == None or head.next == None:return headi = headj = head.nexti_pre = heady = headwhile i != None and j != None:if i == head:i.next = j.nextj.next = iy = ji_pre = iif i.next != None and j.next.next.next != None:i = i.nextj = j.next.next.nextelse:return yelse:i.next = j.nextj.next = ii_pre.next = ji_pre = iif i.next != None and j.next.next.next != None:i = i.nextj = j.next.next.nextelse:return yreturn yn = ListNode(1)
n.next = ListNode(2)
n.next.next = ListNode(3)
n.next.next.next = ListNode(4)p = swapPairs(n)
while p != None:print(p.val)p = p.next

  相关解决方案