Merge Two Sorted Lists
아주아주아주 오랜만에
Linked List
를 다뤄볼 수 있는 기회였다.주어진 두 연결 리스트는 이미 정렬되어 있기 때문에,
반복문을 통해 각 연결 리스트의 노드들을 순회하며
작은 값을 가져와서 head에 연결시키며 진행하면 된다.Input인 l1, l2의 마지막 노드까지 다 돌았으면 종료한다.
위 방식대로 풀었는데 실행시간이 상당히 길었다...
추후에 다시 풀어보며 시간을 줄여봐야겠다.
# 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: ListNode, l2: ListNode) -> ListNode: head = ListNode() cur = head while True: print(l1) print(l2) print(head) if l1 is None: if l2 is None: break else: cur.next = ListNode(l2.val) l2 = l2.next cur = cur.next continue if l2 is None: cur.next = ListNode(l1.val) l1 = l1.next cur = cur.next continue if l1.val <= l2.val: cur.next = ListNode(l1.val) l1 = l1.next else: cur.next = ListNode(l2.val) l2 = l2.next cur = cur.next return head.next
멋진 글이네요!