-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Linked List.cpp
65 lines (51 loc) · 1.02 KB
/
Reverse Linked List.cpp
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
/*
Reverse Linked List
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
*/
#include<iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
if (!head || !head->next)return head;
while (head != NULL){
ListNode* temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
return prev;
}
};
void PrintList(ListNode* head){
if (!head)return;
while (head != NULL){
cout << head->val;
head = head->next;
cout << "->";
}
cout << "NULL";
cout << endl;
}
void main()
{
ListNode* node0 = new ListNode(0);
ListNode* node1 = new ListNode(1);
ListNode* node2 = new ListNode(2);
node0->next = node1;
node1->next = node2;
node2->next = NULL;
PrintList(node0);
Solution mySolu;
PrintList(mySolu.reverseList(node0));
}