[leetcode] 21. Merge Two Sorted Lists
2021. 8. 10. 19:00ㆍ노트/Algorithm : 알고리즘
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:
Input:
l1 = [1,2,4],
l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input:
l1 = [],
l2 = []
Output: []
Example 3:
Input:
l1 = [],
l2 = [0]
Output: [0]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
l3 = []
while (l1 and l2) : # 두 ListNode가 모두 빈 리스트 여야 while 문 멈춤
# print(l1.val)
# print(l2.val)
if l1.val <= l2.val:
l3.append(l1.val)
l1 = l1.next
else:
l3.append(l2.val)
l2 = l2.next
if l1 is not None:
t = l1
else:
t = l2
while t:
l3.append(t.val)
t = t.next
print(l3)
head = ListNode(None)
node = head
while l3:
a = l3.pop(0)
one = ListNode(a)
node.next = one
node = one
return head.next # 맨 처음껄 리턴해야지 중간꺼 보는거 아님!
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[leetcode] 42. Trapping Rain Water (0) | 2022.11.02 |
---|---|
리스트에서 최솟값 찾기 구현 (0) | 2021.08.11 |
[leetcode] 20. Valid Parentheses (0) | 2021.08.10 |
[leetcode] 14. Longest Common Prefix (0) | 2021.08.10 |
[leetcode] 13. Roman to Integer (0) | 2021.08.06 |