ETH官方钱包

前往
大廳
主題

[LeetCode] 24.Swap Nodes in Pairs

テリ君(桃夫模式) | 2023-05-16 19:07:22 | 巴幣 4 | 人氣 274

題目:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

(題目短我就丟上來ㄅ)

class ListNode(object):
     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next

class Solution(object):
    def swapPairs(self, head):
        temp = ListNode(None, head)
        prev, cur = temp, head
        while cur and cur.next:
            prev.next = cur.next
            cur.next = cur.next.next
            prev.next.next = cur
            prev, cur = cur, cur.next
        return temp.next

#for test
node = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))

sol = Solution().swapPairs(node)

while sol:
    print(sol.val, end=" ")
    sol = sol.next

LinkedList 真的是我很不拿手的部分
不過用array的換位概念應該是一樣的?
反正就是先把prev和cur的搞好
然後回傳temp.next指到新的ListNode
就是題目要的東西了

這個要多練...吧?
不過LinkedList實際應用我真的沒那麼熟悉

創作回應

更多創作