1. 程式人生 > 其它 >【LeetCode】24.兩兩交換連結串列中的節點

【LeetCode】24.兩兩交換連結串列中的節點

24.兩兩交換連結串列中的節點

知識點:連結串列

題目描述

給你一個連結串列,兩兩交換其中相鄰的節點,並返回交換後連結串列的頭節點。你必須在不修改節點內部的值的情況下完成本題(即,只能進行節點交換)。

示例
示例 1:
輸入:head = [1,2,3,4]
輸出:[2,1,4,3]

示例 2:
輸入:head = []
輸出:[]

示例 3:
輸入:head = [1]
輸出:[1]


解法一:迭代

兩兩交換連結串列中的節點,所以每次都需要成對的,並且要判斷一下這成對的後面是不是成對的
if是,那能夠繼續迴圈
if不是,那證明後面只有一個或者沒有了,處理一下末尾即可了

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        pre = head
        cur = head.next
        dummyhead = cur
        while cur.next and cur.next.next:
            next_node = cur.next
            cur.next = pre
            pre.next = next_node.next
            pre = next_node
            cur = next_node.next
        last = cur.next
        cur.next = pre
        pre.next = last
        return dummyhead