LeetCode 24 Swap Nodes in Pairs (Python)

Posted by 小明MaxMing on December 28, 2020

题目

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节点指向头,之后的结点两两交换

代码

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummy = ListNode(0)
        res = dummy
        dummy.next = head
        while dummy.next and dummy.next.next:
            first = dummy.next
            second = dummy.next.next
            first.next = second.next
            second.next = first
            dummy.next = second
            dummy = dummy.next.next
        return res.next

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅