-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackLinkedList.cpp
More file actions
110 lines (94 loc) · 1.5 KB
/
StackLinkedList.cpp
File metadata and controls
110 lines (94 loc) · 1.5 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
98
99
100
101
102
103
104
105
106
107
108
109
110
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
int size = 0;
struct Node *next;
}*top=NULL;
void push(int x)
{
struct Node *t = new Node();
if(t==NULL)
{
printf("Stack Overflow\n");
return;
}
t->data = x;
t->next = top;
top = t;
t->size++;
}
int pop()
{
if(top == NULL)
{
printf("Stack is Empty\n");
return -1;
}
else{
Node *p;
p = top;
top = top->next;
int x = p->data;
delete p;
return x;
}
}
int topElement()
{
if(top == NULL)
{
printf("Stack is empty\n");
return -1;
}
else
{
return top->data;
}
}
int peek(int pos)
{
if(top == NULL)
{
printf("Stack is empty\n");
return -1;
}
Node *p = top;
for(int i=1; i<pos; i++){
p = p->next;
if(p->next==NULL)
{
printf("Not found\n");
return -1;
}
}
return p->data;
}
void display()
{
struct Node *p;
p = top;
printf("Stack : \n");
while(p != NULL)
{
printf("%d\n", p->data);
p = p->next;
}
}
int main()
{
push(10);
push(20);
push(40);
push(30);
push(70);
display();
cout << "Top : " << topElement() << endl;
cout << "Peek @ 3 : " << peek(3) << endl;
pop();
pop();
display();
cout << "Top : " << topElement() << endl;
cout << "Peek @ 4 : " << peek(4) << endl;
}