forked from bgopesh/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.cpp
105 lines (83 loc) · 1.34 KB
/
stack.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
struct Node
{
int data;
Node *next;
};
struct Node * top =nullptr;
void push(int data)
{
struct Node * newnode = new Node();
if(top == nullptr)
{
newnode->data =data;
newnode->next =nullptr;
top= newnode;
}
else
{
newnode->data= data;
newnode->next =top;
top=newnode;
}
}
void pop()
{
struct Node* newtop;
if(top == nullptr)
{
cout << "nothing to pop" <<endl;
return;
}
if(top->next ==nullptr)
{
delete top;
top=nullptr;
return;
}
newtop = top->next;
cout << "popped: " << top->data <<endl;
delete top;
top = newtop;
cout << "new top is: " <<top->data <<endl;
}
void displayStack()
{
if(top ==nullptr)
{
cout << "empty stack" <<endl;
return;
}
struct Node * ptr = top;
while(ptr !=nullptr)
{
cout << ptr->data <<endl;
ptr=ptr->next;
}
}
void topOfStack()
{
cout << "top data is "<<top->data <<endl;
}
int main()
{
push(10);
push(20);
push(30);
push(40);
push(50);
topOfStack();
displayStack();
pop();
topOfStack();
pop();
topOfStack();
displayStack();
pop();
topOfStack();
pop();
displayStack();
pop();
displayStack();
pop();
return 0;
}