兩兩交換鏈表中的節點

大神的遞歸解法:

# 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 head == None or head.next == None:
            return head
        l1 = head.next
        head.next = self.swapPairs(l1.next)
        l1.next =head
        return l1

# 每次跳躍兩個節點
# 遵循了
# temp = head.next
# head.next = ***
# *** = temp

我的解法(沒有換節點,只是換了值):

# 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:
        self.swap(head)
        return head
        
    def swap(self, head: ListNode) -> ListNode:
        
        if head and head.next:
            t = head.val
        else:
            return 
        head.val = head.next.val
        head.next.val = t
        self.swap(head.next.next)

 

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