-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path58.LinkedList_reversingLinkedList.cpp
87 lines (73 loc) · 1.37 KB
/
58.LinkedList_reversingLinkedList.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
79
80
81
82
83
84
85
86
87
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node* first = new node;
void create(node* p){
int num;
cout<<"enter number of elements in linked list: ";
cin>>num;
cout<<"enter "<<num<<" elements: ";
cin>>p->data;
for(int i=1;i<num;i++){
node* temp = new node;
cin>>temp->data;
temp->next = p->next;
p->next = temp;
p = temp;
}
}
void display(node* p){
cout<<endl;
while(p){
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
void reverse(node* p){
node *prev = NULL;
node *curr,*temp;
while(p){
curr = new node;
curr->data = p->data;
curr->next = prev;
prev = curr;
temp = p;
p = p->next;
delete temp;
}
first = curr;
}
void reverse_inplace(node* p){
node* q = NULL;
node* temp;
while(p){
temp = p->next;
p->next = q;
q = p;
p = temp;
}
first = q;
}
void reverse_recursive(node* q, node* p){
if(p!=NULL){
reverse_recursive(p,p->next);
p->next = q;
} else{
first = q;
}
}
int main(){
create(first);
display(first);
reverse(first);
display(first);
reverse_inplace(first);
display(first);
node* temp = NULL;
reverse_recursive(temp,first);
display(first);
}