Skip to content

Commit 386bbd8

Browse files
committed
Stack Implementation
1 parent 452379b commit 386bbd8

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ This is a repository containing various C++ Programs to understand the basic con
1616

1717
C++ Code for implementing a queue using single stack (using recursion).
1818

19+
* [Stack Implementation](https://github.com/altruistcoder/Data-Structures/blob/master/Stack/stack.cpp):
20+
21+
C++ Code for implemention of a stack.
22+
1923
* [Stack Using Two Queues](https://github.com/altruistcoder/Data-Structures/blob/master/Stack/stack_using_two_queues.cpp):
2024

2125
C++ Code for implementing a stack using two queues.

Stack/stack.cpp

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#include <iostream>
2+
#include <stdlib.h>
3+
#define N 100
4+
using namespace std;
5+
6+
class Stack
7+
{
8+
int top, stack[N];
9+
public:
10+
Stack()
11+
{
12+
top = -1;
13+
}
14+
void push(int data)
15+
{
16+
if(top==N-1)
17+
{
18+
cout<<"Stack is Full (Stack Overflow) \n";
19+
return;
20+
}
21+
stack[++top] = data;
22+
}
23+
void pop()
24+
{
25+
if(top==-1)
26+
{
27+
cout<<"Stack is Empty, thus cannot pop an element (Stack Underflow) \n";
28+
return;
29+
}
30+
cout<<"The popped item from the stack is: "<<stack[top--]<<endl;
31+
}
32+
void StackTop()
33+
{
34+
if(top==-1)
35+
{
36+
cout<<"Stack is Empty, thus no TOP Element present \n";
37+
return;
38+
}
39+
cout<<"The top element present in the stack is: "<<stack[top]<<endl;
40+
}
41+
void traversal()
42+
{
43+
if(top==-1)
44+
{
45+
cout<<"Stack is Empty, thus cannot traverse the stack \n";
46+
return;
47+
}
48+
cout<<"The elements present in the Stack are: \n";
49+
for(int i=top;i>=0;i--)
50+
cout<<stack[i]<<" ";
51+
cout<<endl;
52+
}
53+
int stackSize()
54+
{
55+
cout<<"Size of the Stack: "<<top+1<<endl;
56+
}
57+
};
58+
59+
int main()
60+
{
61+
Stack s;
62+
int x, data;
63+
do
64+
{
65+
cout<<"\nMain Menu \n";
66+
cout<<"1. Insertion to Stack (Push Operation) \n";
67+
cout<<"2. Deletion from Stack (Pop Operation) \n";
68+
cout<<"3. Return Top Element from Stack \n";
69+
cout<<"4. Traversal of the elements of the Stack \n";
70+
cout<<"5. Size of Stack\n";
71+
cout<<"6. Quit \n";
72+
cout<<"Enter your choice (1-6): ";
73+
cin>>x;
74+
switch(x)
75+
{
76+
case 1: cout<<"Enter the value to be inserted in Stack: ";
77+
cin>>data;
78+
s.push(data);
79+
break;
80+
case 2: s.pop();
81+
break;
82+
case 3: s.StackTop();
83+
break;
84+
case 4: s.traversal();
85+
break;
86+
case 5: s.stackSize();
87+
break;
88+
case 6: exit(0);
89+
default: cout<<"Invalid Choice Entered\n";
90+
}
91+
}
92+
while(true);
93+
return 0;
94+
}

0 commit comments

Comments
 (0)