Stack:Push,Pop, is empty
A stack is an
Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of
cards or a pile of plates, etc. A real-world stack allows operations at one end
only. For example, we can place or remove a card or plate from the top of the
stack only.
Basic
Operations:
Stack
operations may involve initializing the stack, using it and then
de-initializing it. Apartfrom these
basic stuffs, a stack is used for the following two primary operations −
Ø push
()− Pushing (storing) an element on the stack.
Ø pop
()− Removing (accessing) an element from the stack.
To
use a stack efficiently, we need to check the status of stack as well. For the
same purpose, the following functionality is added to stacks −
Ø Peek
() − get the top data element of the stack, without removing it.
Ø isFull
() − check if stack is full.
Ø isEmpty
() − check if stack is empty
Code#1:
#include
<iostream>
using
namespace std;
int
stack[100], n=100, top=-1;
void
push(int val) {
if(top>=n-1)
cout<<"Stack
Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void
pop() {
if(top<=-1)
cout<<"Stack
Underflow"<<endl;
else {
cout<<"The popped element is
"<< stack[top] <<endl;
top--;
}
}
void
display() {
if(top>=0) {
cout<<"Stack elements
are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<"
";
cout<<endl;
} else
cout<<"Stack is empty";
}
int
main() {
int ch, val;
cout<<"1) Push in
stack"<<endl;
cout<<"2) Pop from
stack"<<endl;
cout<<"3) Display
stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice:
"<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be
pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid
Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
ABOUT THE AUTHOR
Hello We are OddThemes, Our name came from the fact that we are UNIQUE. We specialize in designing premium looking fully customizable highly responsive blogger templates. We at OddThemes do carry a philosophy that: Nothing Is Impossible
.png)
0 comments:
Post a Comment