Skip to content

Commit 4fab8ab

Browse files
author
jinvicky
committed
reverse-linked-list solution
1 parent 3dc3622 commit 4fab8ab

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import java.util.Stack;
2+
3+
class Solution {
4+
/**
5+
* ๋ฆฌ๋ฒ„์Šค์™€ ๋™์ผํ•œ ํ›„์ž…์„ ์ถœ ๊ตฌ์กฐ๋ฅผ ์ƒ๊ฐํ–ˆ๊ณ  ๊ทธ๋ž˜์„œ ์ž๋ฃŒ๊ตฌ์กฐ๋กœ ์Šคํƒ์„ ๊ฒฐ์ •ํ–ˆ๋‹ค.
6+
* ์‚ฌ์ดํด ๋ฌธ์ œ๋ฅผ ์—ผ๋‘ํ•ด ๋‘๊ณ  ์กฐ๊ฑด์„ ์„ค๊ณ„ํ–ˆ์ง€๋งŒ ์‚ฌ์ดํด์„ ๋Š๋Š” ์œ„์น˜๊ฐ€ ํ‹€๋ ค์„œ ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค.
7+
*/
8+
public ListNode reverseList(ListNode head) {
9+
if (head == null) return null;
10+
11+
Stack<ListNode> stack = new Stack<>();
12+
while (head != null) {
13+
stack.push(head);
14+
head = head.next;
15+
}
16+
17+
ListNode newHead = stack.pop(); // ์ •๋‹ต ๋ฐ˜ํ™˜์šฉ
18+
ListNode current = newHead; // ํฌ์ธํ„ฐ๋ฅผ ๊ฐฑ์‹ ํ•˜๋ฉด์„œ ๊ณ„์‚ฐํ•˜๊ธฐ์šฉ (์†Œ์œ„ ๋”๋ฏธ ํฌ์ธํ„ฐ)
19+
20+
while (!stack.isEmpty()) {
21+
current.next = stack.pop();
22+
current = current.next; // โ† ์ˆ˜์ •: ์ž๊ธฐ ์ž์‹  ๊ฐ€๋ฆฌํ‚ค๋Š” ๋Œ€์‹  ์•ž์œผ๋กœ ์ด๋™
23+
}
24+
current.next = null; // ๋งˆ์ง€๋ง‰ tail ์ •๋ฆฌ
25+
return newHead;
26+
}
27+
}

0 commit comments

Comments
ย (0)