leecode24

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
newhead = ListNode(0)
newhead.next = head
l1 = newhead
if l1.next is None:
return head
l2 = newhead.next.next
if l2 is None:
return head
while True:
tmp = l1.next
l1.next = l2
tmp.next = l2.next
l2.next = tmp
l1 = tmp
if l1.next is None:
break
l2 = l1.next.next
try:
l2.next
except:
break
return newhead.next