-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse a linkedlist.cpp
63 lines (62 loc) · 1.08 KB
/
reverse a linkedlist.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
#include<iostream>
using namespace std;
class node {
public:
int data;
node* next;
node() {
data = 0;
next = NULL;
}
node(int val) {
data = val;
next = NULL;
}
};
void insert(node*&head,int const data) {
node* newnode = new node(data);
if (head == NULL) {
head = newnode;
}
else {
node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next= newnode;
}
}
void reverse(node*& head) {
node* current = head;
node* prev = NULL, * next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
void print(node*&head){
node* temp = head;
while (temp != NULL) {
cout << temp->data << "->";
temp = temp->next;
}
cout <<"null" << endl;
}
int main() {
node* head=NULL;
cout << "LinkedList : " << endl;
insert(head, 10);
insert(head, 20);
insert(head, 30);
insert(head, 40);
insert(head, 50);
insert(head, 60);
print(head);
cout << "After Reverse : " << endl;
reverse(head);
print(head);
return 0;
}