解題思路
非遞歸
1.首先兩兩交換想到用三個指針;
2.使用self可以省掉頭結點的聲明
3.只有當一組兩個節點同時存在才進行交換操作
4.交換位置,以b爲核心,更新三根指針
5.最後返回頭結點
代碼:
# 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:
# newH = ListNode(None)
pre, pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next= b, a, b.next
pre = a
return self.next
遞歸解法
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next: # if you use "and" , it will not return if there is one digit
return head
a = head
b = head.next
a.next = self.swapPairs(head.next) # The value it return is b.next;But when swapping positions, a.next should point to b.next;
b.next = a # Swapping positions
return b # After swapping positions, b should be first ListNode
理解:
1.首先找到遞歸的核心判斷條件:判斷每一組數是否存在,由head可知;
2.兩個指針分佈指向每組第一個和第二個節點;
3.交換後a.next應該指向遞歸返回的結果(b.next);
4.交換當前組a,b位置;
5.返回每組b節點