본문 바로가기
IT/LeetCode

[LeetCode] 21. Merge Two Sorted Lists

by 강천구 2022. 7. 21.

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

 

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

 

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

주어진 두 Listd의 숫자들을 Sort하여 하나의 ListNode로 만드는 문제이다.

두 List의 위치를 표시한 후 각 위치의 값을 비교하여 새로운 ListNode에 순서대로 넣는다. 

 

class Solution:
   def mergeTwoLists(self, l1, l2):
       dummy = cur = ListNode(0)
       while l1 and l2:
           if l1.val < l2.val:
               cur.next = l1
               l1 = l1.next
           else:
               cur.next = l2
               l2 = l2.next
           cur = cur.next
       cur.next = l1 or l2
       return dummy.next

 

문제 출처 : https://leetcode.com/problems/merge-two-sorted-lists/

 

Merge Two Sorted Lists - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_21.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[Leetcode] 27. Remove Element  (0) 2022.07.22
[LeetCode] 26. Remove Duplicates from Sorted Array  (0) 2022.07.22
[LeetCode] 20. Valid Parentheses  (0) 2022.07.21
[LeetCode] 14. Longest Common Prefix  (0) 2022.07.21
[LeetCode] 13. Roman to Integer  (0) 2022.07.21

댓글