題目:給你一個鏈表,兩兩交換其中相鄰的節點,並返回交換後鏈表的頭節點。你必須在不修改節點內部的值的情況下完成本題(即,只能進行節點交換)。
示例 1:
輸入:head = [1,2,3,4] 輸出:[2,1,4,3]
示例 2:輸入:head = [] 輸出:[]
示例 3:輸入:head = [1] 輸出:[1]
提示:
鏈表中節點的數目在范圍 [0, 100] 內 0 <= Node.val <= 100
程序說明:若沒有使用啞節點,代碼就如下面的錯誤代碼,會出現若鏈表斷開的情況(具體根據代碼畫圖可知)
全部代碼:
正確代碼:
# 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:
p = ListNode(0)
p.next = head
cur = p
while cur.next and cur.next.next:
node1 = cur.next
node2 = cur.next.next
cur.next = node2
node1.next = node2.next
node2.next = node1
cur = node1
return p.next
錯誤代碼:
# 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 or not head.next:
return head
p = head
cur = head.next
q = cur.next
while cur.next:
p.next = q
cur.next = p
p = q
cur = p.next
q = cur.next
cur.next = p
return head
題目來源:力扣(leetcode)
1. If the following error occu
Geohash One .GeoHash Code intr