Merge Two Link Lists | LeetCode Practice #6

작성자

카테고리:

← 피드로
DEV Community · 睡觉 · 2026-07-14 개발(SW)

睡觉

Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. Both lists are sorted in non-decreasing order. Return the merged linked list.

The linked list is implemented through the class ListNode, which has default attributes val = 0 and next = None. Note that the attribute next stores a node rather than its index.

Python

####Sort as Whole (Runtime: 0ms, Memory: 12.5MB)
    #DECLARE ListNode: Class(val: 0, next: None)
    #DECLARE list1: ARRAY of ListNode
    #DECLARE list2: ARRAY of ListNode
class Solution(object):
    def mergeTwoLists(self, list1, list2):
        whole_link = ListNode(0)
        current = whole_link
        while list1 and list2:
            if list1.val < list2.val:
                current.next = list1
                list1 = list1.next
            else:
                current.next = list2
                list2 = list2.next
            current = current.next
        if list1:
            current.next = list1
        else:
            current.next = list2
        return whole_link.next

Enter fullscreen mode Exit fullscreen mode

Thoughts

I had a rough time with this question. I think the description on LeetCode was quite vague, especially for beginners like me. In the past, I always assumed that the “next” attribute stored an index and worked together with a list. However, it turns out that people simply stuff the whole thing in it.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다