Leetcode 24

Question

Solution

根据题意,不改变结点的值,改变结点的位置。

创建一个指针,需要判断其之后的以及之后的之后的结点是否存在。如果存在,调整顺序.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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:
ans = cur = ListNode(0)
ans.next = head
while cur.next and cur.next.next:
a = cur.next
b = a.next
a.next, b.next, cur.next = b.next, a, b
cur = cur.next.next

return ans.next