-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseList.cpp
More file actions
77 lines (67 loc) · 1.44 KB
/
reverseList.cpp
File metadata and controls
77 lines (67 loc) · 1.44 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Reverse a singly linked list.
* Hint:
* A linked list can be reversed either iteratively or recursively. Could you implement both?
* Created by Liang.XianLong on 2018/4/17.
*/
#include<iostream>
using namespace std;
/**
* 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);
};
/**
* method(1)-验证通过
* 时间复杂度O(n)
* 空间复杂度O(n)
*/
ListNode* Solution::reverseList(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* p = head;
ListNode* q = p->next;
while (q != nullptr) {
ListNode* t = q->next;
q->next = p;
p = q;
q = t;
}
head->next = nullptr;
return p;
}
/**
* method(2)-验证通过
* 时间复杂度O(n)
* 空间复杂度O(n)
*/
/**
ListNode* Solution::reverseList(ListNode *head) {
if (head == NULL || head->next == NULL) return head;
ListNode *newhead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newhead;
}
*/
int main(void) {
ListNode* l = new ListNode(-1);
ListNode* head = l;
for (int i = 0; i < 3; ++i) {
ListNode* temp = new ListNode(i + 1);
l->next = temp;
l = l->next;
}
head = head->next;
Solution s;
s.reverseList(head);
return 0;
}