Skip to content

Commit ec30007

Browse files
reverse linked list solution
1 parent 601ed62 commit ec30007

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

reverse-linked-list/jaejeong1.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
//Definition for singly-linked list.
3+
class ListNode {
4+
int val;
5+
ListNode next;
6+
ListNode() {}
7+
ListNode(int val) { this.val = val; }
8+
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
}
10+
11+
class SolutionReverseLinkedList {
12+
public ListNode reverseList(ListNode head) {
13+
// 풀이: 링크드리스트 방향을 현재 기준으로 뒤집고, 노드를 다음으로 옮기며 반복한다
14+
// next = curr.next
15+
// prev > curr
16+
// prev < curr
17+
// prev = curr
18+
// curr = next
19+
// TC: O(N), head 길이 N만큼
20+
// SC: O(1), prev/curr 2개만 메모리 사용
21+
22+
ListNode prev = null;
23+
ListNode curr = head;
24+
while(curr != null) {
25+
ListNode next = curr.next;
26+
curr.next = prev;
27+
prev = curr;
28+
curr = next;
29+
}
30+
31+
return prev;
32+
}
33+
}

0 commit comments

Comments
 (0)