forked from therohit777/Hacktober_algo_bucket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InverseLinkedList.cpp
81 lines (67 loc) · 1.31 KB
/
InverseLinkedList.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
#include <iostream>
#include <stack>
using namespace std;
//creating linkedlist
struct Node
{
int data;
struct Node *next;
}*first=NULL;
Node *createLL(int *arr, int n)
{
struct Node *last, *temp;
first=new Node();
first->data=arr[0];
first->next=NULL;
last=first;
for(int i=1; i<n; i++)
{
temp=new Node();
temp->data=arr[i];
temp->next=NULL;
last->next=temp;
last=temp;
}
// print the formed linked list
// struct Node *p=first;
// while(p!=NULL)
// {
// cout<<p->data<<" ";
// p=p->next;
// }
return first;
}
// Reverse printing the elements of a linked list
void inverse(struct Node *p, int n)
{
stack<int> s;
//elements stored in stack
struct Node *q=p;
while(q!=NULL)
{
s.push(q->data);
q=q->next;
}
//printing reverse elements
for(int j=0; j<n; j++)
{
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
}
int main()
{
//take input in array
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
//call the function to create linked list
struct Node *LL=createLL(arr,n);
//call the function to inverse the linked list
inverse(LL,n);
}