Skip to content

Commit d998b5a

Browse files
committed
Solution: Reverse Linked List
1 parent 6dd8755 commit d998b5a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

reverse-linked-list/flynn.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 풀이
3+
* - 생략, 주석 참고
4+
*
5+
* Big O
6+
* - N: 주어진 링크드 리스트 `head`의 길이
7+
*
8+
* - Time complexity: O(N)
9+
* - Space complexity: O(1)
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* struct ListNode {
15+
* int val;
16+
* ListNode *next;
17+
* ListNode() : val(0), next(nullptr) {}
18+
* ListNode(int x) : val(x), next(nullptr) {}
19+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
20+
* };
21+
*/
22+
class Solution {
23+
public:
24+
ListNode* reverseList(ListNode* head) {
25+
if (head == nullptr) return head;
26+
// example: a - b - c - d
27+
28+
ListNode* root = new ListNode();
29+
root->next = head;
30+
// root - a - b - c - d
31+
32+
ListNode* p = head;
33+
ListNode* q = p->next;
34+
// root - a - b - c - d
35+
// (p) (q)
36+
37+
while (q != nullptr) {
38+
p->next = q->next;
39+
// root - a - c - d
40+
// b /
41+
q->next = root->next;
42+
// root - a - c - d
43+
// b /
44+
root->next = q;
45+
// root - b - a - c - d
46+
// (q) (p)
47+
q = p->next;
48+
// root - b - a - c - d
49+
// (p) (q)
50+
}
51+
52+
return root->next;
53+
}
54+
};

0 commit comments

Comments
 (0)