iT邦幫忙

0

leetcode with python:24. Swap Nodes in Pairs

  • 分享至 

  • xImage
  •  

好耶不知不覺就來到第100篇文了
之後medium題的占比會越來越高吧
慶祝一下就來繼續寫文了XD
希望未來也能繼續持續下去

題目:

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.)

給定一個linked list,對每兩個連續node進行交換
而且是要Node的變動,不能只是值的交換而已
ex:input: [1,2,3,4]=>output: [2,1,4,3]

這題用遞迴來實作

# 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: Optional[ListNode]) -> Optional[ListNode]:
        if head and head.next:
            temp=head
            temp2=head.next.next
            head=head.next
            head.next=temp
            head.next.next=self.swapPairs(temp2)
 
        return head

先確定head和head.next都不為None(確認有兩個Node進行交換)
用temp存取head,temp2存取head.next.next(下一次交換的head)

接著將head改為head.next,head.next透過temp變為原head
讓結構變為原head.next->原head

完成了一次交換,接下來進行下一次
用temp2存好的原head.next.next進行遞迴
使其變為新head.next.next(已進行完交換)

整個過程完成後回傳新head
剛好遞迴最外層回傳的是新linked list的頭
最後執行時間24ms(faster than 99.47%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言