#迭代
#1.point.next = swap2
#2.swap1.next = swap2.next
#3.swap2.next = swap1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = ListNode(-1)#设置蓄力节点,此时为-1或者0都不影响
dummy.next = head
point = dummy
while (point.next and point.next.next) :#如图所示
swap1 = point.next
swap2 = point.next.next
point.next = swap2
swap1.next = swap2.next
swap2.next = swap1
point = swap1
return dummy.next
#递归
#由于每次都是俩俩交换,很有规律性
#递归真属于一看就会,一做就废
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
l1 = head.next
head.next = self.swapPairs(head.next.next)
l1.next = head
return l1
