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?

21.Merge Two Sorted Lists

Posted at

問題内容

2つの連結リスト(それぞれ昇順)を一つの連結リストにまとめる

解答例

sample
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        
        dummy = ListNode()
        cur = dummy

        while list1 and list2:
            if list1.val > list2.val:
                cur.next = list2
                list2 = list2.next
            else:
                cur.next = list1
                list1 = list1.next

            cur = cur.next

        if list1:
            cur.next = list1
        else:
            cur.next = list2

        return dummy.next

個人的ポイント

  • 処理の出発点はダミーノードを作ること
  • 連結リストを扱うときは、カーソルによる論理的なノードの繋がりを考える
  • 継続条件は「両方の連結リストに要素が残っている」とすると、終盤の処理が簡単になる
  • 戻り値はダミーノードではなく連結リストの先頭になるよう注意
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?