-
21. Merge Two Sorted ListsLeetcode 2021. 5. 11. 15:40
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]
Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both l1 and l2 are sorted in non-decreasing order.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ flag = True res = ListNode(0) head = res if l1 is None and l2 is None: return None elif l1 is None: return l2 elif l2 is None: return l1 while flag: if l1.val < l2.val: res.next = l1 l1 = l1.next else: res.next = l2 l2 = l2.next res = res.next if l1 is None: res.next = l2 flag = False elif l2 is None: res.next = l1 flag = False return head.next- 링크드 리스트 단순 순회문제
'Leetcode' 카테고리의 다른 글
23. Merge k Sorted Lists (0) 2021.05.18 22. Generate Parentheses (0) 2021.05.18 20. Valid Parentheses (0) 2021.05.10 19. Remove Nth Node From End of List (0) 2021.05.10 18. 4Sum (0) 2021.05.10