-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLinkedListReverse.cpp
More file actions
97 lines (97 loc) · 1.71 KB
/
LinkedListReverse.cpp
File metadata and controls
97 lines (97 loc) · 1.71 KB
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
88
89
90
91
92
93
94
95
96
97
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
void getRev(struct node *head)
{
if(head==NULL)
{
return;
}
getRev(head->next);
printf("%d ",head->data);
}
/*void print(struct node *head)
{
if(head==NULL)
{
return;
}
printf("%d ",head->data);
print(head->next);
}*/
void getStck(struct node *head)
{
stack<node *>st;
struct node *ptr=head;
while(ptr!=NULL)
{
st.push(ptr);
ptr=ptr->next;
}
while(!st.empty())
{
struct node *p=st.top();
cout<<p->data<<" ";
st.pop();
}
}
int getNode(struct node *head,int p)
{
struct node *ptr=head;
int i=1;
while(i<p)
{
ptr=ptr->next;
i++;
}
return ptr->data;
}
void getSimpleLoop(struct node *head)
{
struct node *ptr=head;
int cnt=0;
while(ptr!=NULL)
{
cnt++;
ptr=ptr->next;
}
for(int i=cnt;i>0;i--)
{
int p=getNode(head,i);
cout<<p<<" ";
}
}
int main()
{
int n,m;
//cout<<"Enter the number of elements :"<<endl;
scanf("%d",&n);
//cout<<"Enter the elements:"<<endl;
struct node *head = NULL;
struct node *p,*q;
p = (struct node*)malloc(sizeof(struct node));
scanf("%d",&m);
p->data = m;
p->next = NULL;
head = p;
for(int i=1;i<n;i++)
{
scanf("%d",&m);
q=(struct node*)malloc(sizeof(struct node));
q->data=m;
q->next=NULL;
p->next=q;
p=p->next;
//push(&head,m);
}
//print(head);
getRev(head); //using recursion
cout<<endl;
getStck(head); //stack
cout<<endl;
getSimpleLoop(head); // using loop
}