-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverseList
78 lines (62 loc) · 1.06 KB
/
reverseList
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
#include <iostream>
#include <stack>
using namespace std;
struct node{
int data;
node *next;
};
node *head=NULL;
node *last=NULL;
void Insert (int);
void reverseList ();
void PrintList ();
int main() {
int n,d;
//cout<<"Enter the no of nodes in linked list"<<endl;
cin>>n;
//cout<<"Enter the data one by one"<<endl;
for(int i=0;i<n;i++){
cin>>d;
Insert(d);
}
reverseList();
PrintList();
return 0;
}
void PrintList(){
node *ptr=head;
while(ptr!=NULL){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
}
void Insert(int d){
node *ptr;
ptr=new node();
ptr->data=d;
ptr->next=NULL;
if(head==NULL){
head=ptr;
last=head;
return;
}
last->next=ptr;
last=ptr;
}
void reverseList(){
stack<node *> s;
node *ptr=head;
while(ptr!=NULL){
s.push(ptr);
ptr=ptr->next;
}
head=s.top();
s.pop();
ptr=head;
while(!s.empty()){
ptr->next=s.top();
s.pop();
ptr=ptr->next;
}
ptr->next=NULL;
}