题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,对于链表中的内容,就两两交换,这里的两两交换不重合。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head

dummy = ListNode(-1, head)
pre = dummy
while pre.next and pre.next.next:
cur = pre.next
last = cur.next
nxt = last.next
last.next = cur
pre.next = last
cur.next = nxt
pre = cur
return dummy.next