js生成8位隨機字串密碼
阿新 • • 發佈:2020-12-20
24. 兩兩交換連結串列中的節點
Difficulty: 中等
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例 1:
輸入:head = [1,2,3,4]
輸出:[2,1,4,3]
示例 2:
輸入:head = []
輸出:[]
示例 3:
輸入:head = [1]
輸出:[1]
提示:
- 連結串列中節點的數目在範圍
[0, 100]
內 0 <= Node.val <= 100
Solution
# 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: if not head: return None res = pre = ListNode(-1) pre.next = head while head and head.next: tmp = head.next head.next = tmp.next tmp.next = head pre.next = tmp head = head.next pre = tmp.next return res.next