大神的遞歸解法:
# 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)