Skip to content

Commit

Permalink
add post '(Leetcode) 21 - Merge Two Sorted Lists'
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-jonghoonpark committed May 1, 2024
1 parent 72756e0 commit 727437f
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions _posts/2024-05-01-leetcode-21.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
layout: post
title: (Leetcode) 21 - Merge Two Sorted Lists
categories: [스터디-알고리즘]
tags:
[
자바,
java,
linked list,
연결 리스트,
리트코드,
Leetcode,
알고리즘,
algorithm,
neetcode,
]
date: 2024-04-29 13:50:00 +0900
toc: true
---

기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.

[https://neetcode.io/practice](https://neetcode.io/practice)

---

2주간 미션이 나와서 다시 풀기 시작하였다.

[https://leetcode.com/problems/merge-two-sorted-lists/description/](https://leetcode.com/problems/merge-two-sorted-lists/description/)

## 내가 작성한 풀이

두 리스트에서 작은 값을 찾고 작은 값을 새 ListNode에 추가한 뒤 기존의 리스트에서는 지워준다.

```java
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = null;
ListNode tail = null;

while(!(list1 == null && list2 == null)) {
ListNode selected;
if (list1 == null) {
selected = list2;
list2 = list2.next;
} else if (list2 == null) {
selected = list1;
list1 = list1.next;
} else if (list1.val < list2.val) {
selected = list1;
list1 = list1.next;
} else {
selected = list2;
list2 = list2.next;
}

ListNode newNode = new ListNode(selected.val);
if(head == null) {
head = newNode;
} else {
tail.next = newNode;
}

tail = newNode;
}

return head;
}
}
```

### TC, SC

시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다.

0 comments on commit 727437f

Please sign in to comment.