-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206_reverseLL.cpp
50 lines (43 loc) · 886 Bytes
/
206_reverseLL.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
// given the head of a singly Linked LIst , return the reversed list
// TC = O(n) and SC = O(1)
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* curr = head;
Node* nextn;
while(curr != NULL) {
nextn = curr -> next;
curr-> next = prev;
prev = curr;
curr = nextn;
}
return prev;
}
void print(Node* head) {
Node* temp = head;
while(temp!= NULL) {
cout<<temp-> data<<" ";
temp = temp-> next;
}
cout<< endl;
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head = reverseList(head);
print(head);
return 0;
}