Leetcode 24.两两交换链表的节点 (每日一题 20210624)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 24.两两交换链表的节点 (每日一题 20210624)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個鏈表,兩兩交換其中相鄰的節點,并返回交換后的鏈表。你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。示例 1:輸入:head = [1,2,3,4]
輸出:[2,1,4,3]
示例 2:輸入:head = []
輸出:[]
示例 3:輸入:head = [1]
輸出:[1]提示:鏈表中節點的數目在范圍 [0, 100] 內
0 <= Node.val <= 100鏈接:https://leetcode-cn.com/problems/swap-nodes-in-pairsclass Solution:def swapPairs(self, head: ListNode) -> ListNode:p = ListNode(-1)a, b, p.next, tmp = p, p, head, pwhile b.next and b.next.next:a,b = a.next,b.next.nexttmp.next,a.next,b.next = b, b.next, atmp, b = a, areturn p.nextclass Solution:def swapPairs(self, head: ListNode) -> ListNode:if not head or not head.next:return headfirst_node = headsecond_node = head.nextfirst_node.next = self.swapPairs(second_node.next)second_node.next = first_nodereturn second_node
總結
以上是生活随笔為你收集整理的Leetcode 24.两两交换链表的节点 (每日一题 20210624)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 22.括号生成 (每日
- 下一篇: Leetcode 104.二叉树的最大深