관리 메뉴

솜씨좋은장씨

[leetCode] 21. Merge Two Sorted Lists (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 21. Merge Two Sorted Lists (Python)

솜씨좋은장씨 2020. 3. 4. 02:08
728x90
반응형

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        my_l1 = []
        
        while l1 != None:
            my_l1.append(int(l1.val))
            
            l1 = l1.next
            
        while l2 != None:
            my_l1.append(int(l2.val))
            
            l2 = l2.next

        my_l1 = list(sorted(my_l1))
        
        answerList = None
        
        for i in range(len(my_l1)):
            if i == 0:
                answerList = ListNode(my_l1[i])
            else:
                new_node = ListNode(my_l1[i])
                currNode = answerList
                while currNode.next != None:
                    currNode = currNode.next
                currNode.next = new_node
        return answerList

Solution 풀이

my_l1 이라는 list에 입력받은 두 개의 list에서 모든 값을 append해주고

sorted 함수로 정렬한 뒤

answerList 에 추가한 후 return 해주었습니다.

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments