File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 풀이 :
3+ linked-list를 순회하며 stack에 차례대로 push하고 다 넣은 후
4+ pop하면서 역순으로 연결해준다
5+
6+ 노드의 개수 : N
7+
8+ TC : O(N)
9+ 총 2회 while 반복문 O(N + N)
10+
11+ SC : O(N)
12+ 스택은 노드의 개수에 비례
13+ */
14+
15+ /* *
16+ * Definition for singly-linked list.
17+ * struct ListNode {
18+ * int val;
19+ * ListNode *next;
20+ * ListNode() : val(0), next(nullptr) {}
21+ * ListNode(int x) : val(x), next(nullptr) {}
22+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
23+ * };
24+ */
25+
26+ #include < stack>
27+ using namespace std ;
28+
29+ struct ListNode {
30+ int val;
31+ ListNode *next;
32+ ListNode () : val(0 ), next(nullptr ) {}
33+ ListNode (int x) : val(x), next(nullptr ) {}
34+ ListNode (int x, ListNode *next) : val(x), next(next) {}
35+ };
36+
37+ class Solution {
38+ public:
39+ ListNode* reverseList (ListNode* head) {
40+ stack<ListNode*> st;
41+ ListNode dummy;
42+ ListNode* prv = &dummy;
43+ ListNode* cur;
44+
45+ while (head)
46+ {
47+ st.push (head);
48+ head = head->next ;
49+ }
50+
51+ while (!st.empty ())
52+ {
53+ cur = st.top ();
54+ prv->next = cur;
55+ prv = cur;
56+ st.pop ();
57+ }
58+ prv->next = nullptr ;
59+
60+ return dummy.next ;
61+ }
62+ };
You can’t perform that action at this time.
0 commit comments