본문 바로가기
Leetcode

[LeetCode] Merge Two Sorted Lists 파이썬 (linked list)

by YGSEO 2021. 3. 29.
728x90

singly-linked list 에 대해 아직 이해가 부족 더 해봐야 함.

 

# Definition for singly-linked list.
# class ListNode:
#     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
        """
        total = []
        
        while l1 != None:
            total.append(int(l1.val))
            l1 = l1.next
        
        while l2 != None:
            total.append(int(l2.val))
            l2 = l2.next
        
        total = list(sorted(total))
        
        answer = None
        
        for i in range(len(total)):
            if i == 0:
                answer = ListNode(total[i])
            else:
                new_node = ListNode(total[i])
                curr_node = answer
                while curr_node.next != None: # fill all the curr_node's next
                    curr_node = curr_node.next
                curr_node.next = new_node # insert new_node to curr_node.next
        return answer
                
                
                    
        

출처: somjang.tistory.com/entry/leetCode-21-Merge-Two-Sorted-Lists

 

다른 풀이들

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, self.next)


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


if __name__ == "__main__":
    l1 = ListNode(0)
    l1.next = ListNode(1)
    l2 = ListNode (2)
    l2.next = ListNode(3)
    print(Solution().mergeTwoLists(l1, l2))

출처: github.com/jiapengwen/LeetCode/blob/master/Python/merge-two-sorted-lists.py

 

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def my_print(l1: ListNode, l2:ListNode):

    print("l1 : ", end="")
    while l1 is not None:
        print(f'{l1.val} -> ', end="")
        l1 = l1.next
    print()

    print("l2 : ", end="")
    while l2 is not None:
        print(f'{l2.val} -> ', end="")
        l2 = l2.next
    print()


i = 0

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        global i
        i+=1
        print()
        print(f'{i}번째 mergeTowLists')


        if (not l1) or (l2 and l1.val > l2.val):
            print("첫번째 조건문")
            l1, l2 = l2, l1
            my_print(l1, l2)

        if l1:
            print("두번째 조건문")
            l1.next = self.mergeTwoLists(l1.next, l2)

        return l1


l1 = ListNode(1)
l1.next= ListNode(2)
l1.next.next = ListNode(4)

l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)

s = Solution()
answer = s.mergeTwoLists(l1, l2)
while answer is not None:
    print(f'{answer.val} ->', end=" ")
    answer = answer.next

출처: ihp001.tistory.com/72

 

singly-linked listsingly-linked list

728x90

댓글