Post

πŸ’‘ LeetCode 21 - Merge Two Sorted Lists

πŸ’‘ LeetCode 21 - Merge Two Sorted Lists

문제

You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.

μž…μΆœλ ₯ 예제

βœ… 예제 1

1
2
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

βœ… 예제 2

1
2
Input: list1 = [], list2 = []
Output: []

βœ… 예제 3

1
2
Input: list1 = [], list2 = [0]
Output: [0]

μ œμ•½μ‘°κ±΄

  • `The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

μž‘μ„± μ½”λ“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
	public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
		// 1. λ³€μˆ˜ μ„ μ–Έ 및 μ΄ˆκΈ°ν™”
		ListNode resultNode = new ListNode();
		ListNode tempNode = resultNode;
		
		// 2. λ¦¬μŠ€νŠΈμ— κ²°κ³Ό μˆœμ„œλŒ€λ‘œ μΆ”κ°€
		while (list1 != null || list2 != null) {
			if (list1 == null) {
				tempNode.next = list2;
				list2 = list2.next;
			} else if (list2 == null) {
				tempNode.next = list1;
				list1 = list1.next;
			} else {
				if (list1.val <= list2.val) {
					tempNode.next = list1;
					list1 = list1.next;
				} else {
					tempNode.next = list2;
					list2 = list2.next;
				}
			}
			tempNode = tempNode.next;    
		}    
		
		// 3. λ°˜ν™˜
		return resultNode.next;
	}
}

  • ListNodeλŠ” λ¬Έμ œμ—μ„œ μ£Όμ–΄μ§€λŠ” 클래슀둜, 주석을 톡해 μ–΄λ–»κ²Œ μž‘μ„±λ˜μ–΄ μžˆλŠ”μ§€ μ•Œ 수 μžˆμ—ˆλ‹€.
  • μ£Όμ–΄μ§„ νŒŒλΌλ―Έν„°κ°€ λ¬Έμ œμ—μ„œ μ£Όμ–΄μ§„ ListNode μΈμŠ€ν„΄μŠ€κ°€ μ•„λ‹Œ λ°°μ—΄μ΄λ‚˜ Listμ˜€λ‹€λ©΄ Dequeλ₯Ό μ‚¬μš©ν•  수 μžˆμ—ˆμ„ 것 κ°™λ‹€.

회고

  • μ°Έμ‘° κ°œλ…μ„ μ •λ¦¬ν•˜λ©° 둜컬 λ³€μˆ˜λŠ” Stack λ©”λͺ¨λ¦¬μ—, μΈμŠ€ν„΄μŠ€λŠ” Heap λ©”λͺ¨λ¦¬μ— μƒμ„±λœλ‹€λŠ” 점을 μ•Œκ²Œ λ˜μ—ˆλ‹€.
  • μΈμŠ€ν„΄μŠ€λŠ” λ©”μ„œλ“œ μ‹€ν–‰ 쀑간에 null을 μ°Έμ‘°ν•˜λ”λΌλ„ λ°”λ‘œ 사라지지 μ•Šκ³ , λ©”μ„œλ“œκ°€ μ’…λ£Œλ˜λ©΄ λ©”λͺ¨λ¦¬ μƒμ—μ„œ μ—†μ–΄μ§„λ‹€κ³  ν•œλ‹€.
This post is licensed under CC BY 4.0 by the author.