-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseLinkedList.cpp
More file actions
56 lines (51 loc) · 1.24 KB
/
reverseLinkedList.cpp
File metadata and controls
56 lines (51 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack<ListNode *> ss;
while(head){
ss.push(head);
head = head -> next;
}
if(!ss.empty()){
head = ss.top();
ss.pop();
}
ListNode *pre = head, *cur;
while(!ss.empty()){
cur = ss.top();
pre -> next = cur;
pre = cur;
ss.pop();
}
cur -> next = NULL;
return head;
}
ListNode* reverseList(ListNode* head) {
if (!head) return nullptr;
ListNode* newNode = nullptr;
while(head){
ListNode* next = head -> next;
head -> next = newNode;
newNode = head;
head = next;
}
return newNode;
}
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) {
return head;
}
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = nullptr;
return node;
}
};