Skip to content

Commit df9bd02

Browse files
committed
Reverse Linked List
1 parent 4e05063 commit df9bd02

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Time Complexity: O(n)
3+
Space Complexity: O(1)
4+
5+
head에서부터 하나씩 next를 탐색하면서, 연결을 반대로 맺어준다.
6+
*/
7+
8+
/**
9+
* Definition for singly-linked list.
10+
* public class ListNode {
11+
* int val;
12+
* ListNode next;
13+
* ListNode() {}
14+
* ListNode(int val) { this.val = val; }
15+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
16+
* }
17+
*/
18+
class Solution {
19+
public ListNode reverseList(ListNode head) {
20+
if (head == null) {
21+
return null;
22+
}
23+
24+
ListNode curr = head;
25+
ListNode next = head.next;
26+
27+
head.next = null; // 마지막 노드가 될 노드의 next는 null로 세팅
28+
while (next != null) {
29+
ListNode nnext = next.next; // 연결을 끊기 전에, 그 다음 노드를 미리 nnext로 참조해둔다.
30+
next.next = curr; // 연결을 반대로 맺어준다.
31+
curr = next;
32+
next = nnext;
33+
}
34+
35+
return curr;
36+
}
37+
}

0 commit comments

Comments
 (0)