본문 바로가기
LeetCode/Problems

LeetCode 21. Merge Two Sorted Lists

by 벤진[Benzene] 2020. 6. 1.

Problem:

Merge two sorted linked lists and return it as a new sorted 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

 

-Summary-

1. Create a dummy and curr variables to track and merge the two lists.

2. Compare l1 and l2 value. 'curr' will connect to the less value. Update l1 or l2 depends on the result

3. Move the curr position

4. After the loop, connect curr to any left l1 or l2 LinkedList

 

처음엔 어떻게 해야할지 감이 안오다가, Leetcode 의 discussion에서 많은 도움을 받았다.

또한 이번 문제를 풀면서, 아래와 같은 코드 기법도 알게 되었다.

curr.next = l1 or l2
#cur.next = l1 if l1 else l2

 

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글