Data Structure and Algorithms - Stack LIFO
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. Likewise, Stack ADT allows all data operations at one end only. At any given time, we can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation.
Basic Operations
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations −
push() − Pushing or adding or accessing an element on the stack.
pop() − Removing or delete or accessing an element from the stack.
When data is PUSH onto stack.
To use a stack efficiently, we need to check the status of stack whether is it full or not. 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.
peek()
Algorithm of peek() function −
begin procedure peek return stack[top] end procedure
isfull()
Algorithm of isfull() function −
begin procedure isfull if top equals to MAXSIZE return true else return false endif end procedure
isempty()
Algorithm of isempty() function −
begin procedure isempty if top less than 1 return true else return false endif end procedure
using namespace std;
ReplyDeleteclass stack {
int stk[5];
int top;
public:
stack()
{
top = -1;
}
void push(int x)
{
if (top >= 4) {
cout << "stack overflow";
return;
}
stk[++top] = x;
cout << "inserted " << x;
}
void pop()
{
if (top < 0) {
cout << "stack underflow";
return;
}
cout << "deleted " << stk[top--];
}
void display()
{
if (top < 0) {
cout << " stack empty"; return; } for (int i = top; i >= 0; i--)
cout << stk[i] << " ";
}
};
int main()
{
int ch;
stack st;
while (1) {
cout << "\n1.push 2.pop 3.display 4.exit\nEnter ur choice: "; cin >> ch;
switch (ch) {
case 1:
cout << "enter the element: "; cin >> ch;
st.push(ch);
break;
case 2:
st.pop();
break;
case 3:
st.display();
break;
case 4:
exit(0);
}
}
}
#include
ReplyDelete#include