written 2.9 years ago by |
Stack : -
A stack is one of the most commonly used data structure.
A stack, also called Last In First Out (LIFO) system, is a linear list in which insertion and deletion can take place only at one end, called top.
This structure operates in much the same way as stack of trays.
If we want to remove a tray from stack of trays it can only be removed from the top only.
- The insertion and deletion operation in stack terminology are known as PUSH and POP operations.
Following operation can be performed on stack :
Create stack (s) : To create an empty stack s.
PUSH (s, i) : To push an element i into stack s.
POP (s) : To access and remove the top element of the stack s.
Peek (s) : To access the top element of stack s without removing it from the stack s.
Overflow : To check whether the stack is full.
Underflow : To check whether the stack is empty.
Applications of Stacks are : -
Stacks can be used for expression evaluation.
Stacks can be used to check parenthesis matching in an expression.
Stacks can be used for Conversion from one form of expression to another.
Stacks can be used for Memory Management.
Stack data structures are used in backtracking problems.
Stack Pointer:
It is used as a memory pointer.
It points to a memory location in read/write memory, called the stack.
It is always incremented / decremented by 2 during push and pop operation.
A stack pointer is a small register that stores the address of the last program request in a stack.
A stack is a specialized buffer which stores data from the top down. As new requests come in, they "push down" the older ones.
Array implementation of stack in C : -
#include<stdio.h>
#include<conio.h>
#define MAX 50
int stack [MAX + 1], top = 0 ;
void main( )
{
clrscr( );
void create( ), traverse( ), push( ), pop( );
create( );
printf(“\n stack is:\n”);
traverse( );
push( );
printf(“After Push the element in the stack is :\n”);
traverse( );
pop( );
printf(“After Pop the element in the stack is :\n”);
traverse( );
getch( );
}
void create( )
{
char ch;
do
{
top ++;
printf(“Input Element”);
scanf (“%d”, stack[top]);
printf(“Press<Y>for more element\n”);
ch = getch( );
}
while (ch == ‘Y’ )
}
void traverse( )
{
Data Structure 2–5 A (CS/IT-Sem-3)
int i ;
for(i = top; i > 0; – –i)
printf(“%d\n”, stack[i]);
}
void push( )
{
int m;
if(top == MAX)
{
printf(“Stack is overflow”);
return;
}
printf(“Input new element to insert”);
scanf(“%d”, &m) ;
top++;
stack[top] = m;
}
void pop( )
{
if(top == 0)
{
printf(“Stack is underflow\n”);
return;
}
stack[top] = ‘\0’ ;
top – – ;
}