0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

1日1回感謝のleetcode #7 [206. Reverse Linked List]

0
Posted at

勉強してる時はずっと机にくっついてるのでディフューザーを買いました。最近は風が心地よく窓を開けてると風と香りが癒してくれます。最高。
今日もやっていきましょう。

※1日1leetcodeをやる理由は第1回を見てください
1日1回感謝のleetcode #1 [141. Linked List Cycle]

206. Reverse Linked List

おや、Linked Listの問題か?って思ったけどstackでも考えられる問題でした。与えられたリストを逆順にして返すっていうまさにLIFOのお手本のような問題。
とりあえずさくっと実装。

class Solution:
    def reverseList(self, head: ListNode | None) -> ListNode | None:
        stack = []
        cur = head
        while cur:
            stack.append(cur.val)
            cur = cur.next
        cur = head
        while cur:
            cur.val = stack.pop()
            cur = cur.next
        return head

問題なくAcceptedでした。
ただWhileを2回回してることやcur = headを2回実行してるところなど、美しくないコードです。
もうちょっと考えてみます。

class Solution:
    def reverseList(self, head: ListNode | None) -> ListNode | None:
        prev = None
        while head:
            next_n = head.next
            head.next = prev
            prev = head
            head = next_n   
        return prev

ちょっと混乱しましたが、この実装なら時間計算量O(n)の空間計算量O(1)でいけてそうです。
ただ、この解き方だとstackを利用しているわけじゃないのでstackを学ぶって意味では1つめの解き方が理想なのかもしれません。

ではまた明日。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?