【Leetcode24 兩兩交換鏈表中的節點】

題目描述

在這裏插入圖片描述

解題思路

解法一:迭代法

原鏈表
在這裏插入圖片描述
添加空頭後的鏈表
在這裏插入圖片描述
第一次交換

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

python代碼

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        thead = ListNode(-1)
        thead.next = head
        c = thead
        while c.next and c.next.next:
            a = c.next
            b = c.next.next
            c.next = b
            a.next = b.next
            b.next = a
            c = c.next.next
        return thead.next

解法二

將鏈表的值存到列表中,再兩兩翻轉

python代碼

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        a = []
        tem = ListNode(-1)
        p = tem
        # 把鏈表的值存儲到列表當中
        while head:
            a.append(head.val)
            head = head.next
        b = len(a)//2
        # 兩兩進行交換
        for i in range(0,b*2,2):
            a[i],a[i+1] = a[i+1],a[i]
        # 再重新創建鏈表
        for j in a:
            p.next = ListNode(j)
            p = p.next
        return tem.next

s = Solution()
res = s.swapPairs(head)
print(res)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章