Skip to content

Commit 40625c5

Browse files
committed
7주차 문제 풀이
1 parent 83e3f10 commit 40625c5

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed

reverse-linked-list/leehyeyun.js

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*
2+
주어진 단일 연결 리스트(singly linked list)는
3+
각 노드가 하나의 값(val)과 다음 노드를 가리키는 포인터(next)를 가진다.
4+
5+
리스트의 첫 번째 노드는 head로 주어진다.
6+
7+
문제 목표:
8+
- 주어진 단일 연결 리스트의 노드 순서를 완전히 반대로 뒤집는다.
9+
- 뒤집힌 연결 리스트의 새로운 head를 반환한다.
10+
11+
중요한 조건:
12+
1) 단일 연결 리스트이므로 노드는 이전 노드를 직접 참조하지 않는다.
13+
2) 값의 순서를 바꾸는 것이 아니라, 노드 간 연결(next)의 방향을 변경해야 한다.
14+
3) 모든 노드는 그대로 사용하며 새 노드를 생성할 필요는 없다.
15+
16+
즉,
17+
원래 리스트:
18+
1 → 2 → 3 → 4 → 5 → null
19+
20+
뒤집은 결과:
21+
5 → 4 → 3 → 2 → 1 → null
22+
23+
입력 형식:
24+
- head: 단일 연결 리스트의 첫 번째 노드 (ListNode)
25+
- ListNode는 다음 구조를 가진다:
26+
{
27+
val: 정수,
28+
next: ListNode | null
29+
}
30+
31+
제약 조건:
32+
- 노드의 개수는 0 이상 5000 이하
33+
- 각 노드의 값은 -5000 이상 5000 이하
34+
35+
출력 형식:
36+
- 뒤집힌 연결 리스트의 첫 번째 노드 (ListNode)
37+
38+
예시:
39+
40+
Example 1
41+
입력: head = [1,2,3,4,5]
42+
출력: [5,4,3,2,1]
43+
44+
Example 2
45+
입력: head = [1,2]
46+
출력: [2,1]
47+
48+
Example 3
49+
입력: head = []
50+
출력: []
51+
*/
52+
53+
54+
function ListNode(val, next) {
55+
this.val = val === undefined ? 0 : val;
56+
this.next = next === undefined ? null : next;
57+
}
58+
59+
/**
60+
* @param {ListNode} head
61+
* @return {ListNode}
62+
*/
63+
var reverseList = function(head) {
64+
let prev = null;
65+
let current = head;
66+
67+
while (current !== null) {
68+
let next = current.next;
69+
current.next = prev;
70+
prev = current;
71+
current = next;
72+
}
73+
74+
return prev;
75+
};
76+
77+
// ===== 테스트 1 : [1,2,3,4,5]
78+
const head1 =
79+
new ListNode(1,
80+
new ListNode(2,
81+
new ListNode(3,
82+
new ListNode(4,
83+
new ListNode(5)
84+
)
85+
)
86+
)
87+
);
88+
89+
// ===== 테스트 2 : [1,2]
90+
const head2 = new ListNode(1, new ListNode(2));
91+
92+
// 결과 출력용
93+
function printList(head) {
94+
const result = [];
95+
let cur = head;
96+
97+
while (cur) {
98+
result.push(cur.val);
99+
cur = cur.next;
100+
}
101+
102+
console.log(result);
103+
}
104+
105+
// 실행
106+
printList(reverseList(head1));
107+
printList(reverseList(head2));
108+
109+

0 commit comments

Comments
 (0)