-
Notifications
You must be signed in to change notification settings - Fork 134
/
ReverseSLL.cpp
80 lines (61 loc) · 1.55 KB
/
ReverseSLL.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
66
67
68
69
70
71
72
73
74
75
76
77
78
// Reverse a singly linked list
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() {
this->next = NULL;
}
Node(int data) {
this->data = data;
this->next = NULL;
}
};
class LinkedList {
public:
Node* head = NULL;
void insert_at_beg(int data){
Node* temp = new Node(data);
temp->next = this->head;
this->head = temp;
}
void print_data(){
Node* itr = this->head;
while(itr != NULL){
cout << itr->data << " ";
itr = itr->next;
}
cout << endl;
}
};
void reverse(LinkedList *ll){
// if linked list is empty or has only 1 node
if(ll->head == NULL || ll->head->next == NULL) return;
Node *curr_ptr = ll->head, *next_ptr, *prev_ptr = NULL;
while(curr_ptr != NULL){
next_ptr = curr_ptr->next;
curr_ptr->next = prev_ptr;
prev_ptr = curr_ptr;
curr_ptr = next_ptr;
}
// update to the new head
ll->head = prev_ptr;
}
int main() {
LinkedList* ll = new LinkedList();
// Create Linked list
ll->insert_at_beg(6);
ll->insert_at_beg(5);
ll->insert_at_beg(4);
ll->insert_at_beg(3);
ll->insert_at_beg(2);
ll->insert_at_beg(1);
cout << "Linked list before reverse: " << endl;
ll->print_data();
reverse(ll);
cout << "Linked list after reverse: " << endl;
ll->print_data();
return 0;
}