0% found this document useful (0 votes)
2 views

Stack

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, allowing insertion and removal of elements at the top. It can be implemented using arrays or linked lists, with basic operations including push, pop, peek, isEmpty, isFull, and display. The document also discusses multiple stacks, their applications, and provides algorithms for stack operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Stack

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle, allowing insertion and removal of elements at the top. It can be implemented using arrays or linked lists, with basic operations including push, pop, peek, isEmpty, isFull, and display. The document also discusses multiple stacks, their applications, and provides algorithms for stack operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Stack

A stack is a non-primitive linear data structure.

It is an ordered list in which the insertion of a new element and removal of


an existing element takes place at the same end which is called the top.

pile of plates stack of chairs stack of plates

Stack is also called LAST-IN-FIRST-OUT (LIFO) type of data structure.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


To implement the stack, it is required to maintain the pointer to the top of
the stack, which is the last element to be inserted because we can access
the elements only on the top of the stack.

Stacks can be implemented either using an array or a linked list.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Basic Operations on Stack
In order to make manipulations in a stack, there are certain operations
provided to us.

➢ push( ) to insert an element into the stack

➢ pop( ) to remove an element from the stack

➢ peek( ) returns the top element of the stack.

➢ isEmpty( ) returns true if stack is empty else false.

➢ isFull( ) returns true if stack is full else false.

➢ display( ) to print all elements of the stack.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Stacks implementation using an array:
#define MAX 10
int stack_arr[MAX];
int top = -1;

(a) Empty stack (b) Push 5 (c) Push 10


top = -1 top = 0 top = 1
5 5 10
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] [4]

(d) Push 15 (e) Push 20 (f) Push 25


top = 2 top = 3 top = 4
5 10 15 5 10 15 20 5 10 15 20 25
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] [4]

(g) Pop 25 (h) Pop 20 (i) Pop 15


top = 3 top = 2 top = 1
5 10 15 20 5 10 15 5 10
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] [4]
(j) Push 30 (k) Pop 30 (L) Pop
10
top = 2 top = 1 top = 0
5 10 30 5 10 5
[0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [0] [1] [2] [3] [4]
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Push Operation: Push adds an item to the stack. If the stack is full, then it is
said to be an Overflow condition. If TOP = -1, then it indicates that the stack
is empty and if TOP = MAX -1, then the stack is full.

Algorithm to PUSH an element in void push(int item)


a stack {
if(isFull())
Step 1: IF TOP = MAX-1, then {
PRINT “OVERFLOW” printf(“stack overflow”);
Goto Step 4 return;
[END OF IF] }
Step 2: SET TOP = TOP + 1 top = top + 1;
Step 3: SET STACK[TOP] = VALUE stack_arr[top] = item;
Step 4: END } Stack_arr[++top] = item;
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Pop Operation: Pop removes an item from the top of the stack. If the stack
is empty, then it is said to be an Underflow condition.

Algorithm to POP an element int pop( )


from a stack {
int item;
Step 1: IF TOP = NULL, then if(isEmpty())
PRINT “UNDERFLOW” {
Goto Step 4 printf(“stack underflow”);
[END OF IF] return;
Step 2: SET VAL = STACK[TOP] }
Step 3: SET TOP = TOP - 1 item = stack_arr(top);
Step 4: END top = top-1;
return item;
} return stack_arr[top--];
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Peek Operation: return the top element of the stack.
Algorithm for Peek Operation int peek( )
{
Step 1: IF TOP = NULL, then if(isEmpty())
PRINT “STACK IS EMPTY”
{
Go TO Step 3
[END OF IF] printf(“stack underflow”);
Step 2: RETURN STACK[TOP] return;
Step 3: END }
return stack_arr(top);
}

isFull( ) Operation

int isFull( )
{
if(top = MAX-1)
return 1;
else
return 0;
}
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
isEmpty( ) Operation int isEmpty( )
{
if(top = -1)
return 1;
else
return 0;
}

display( ): print all elements of the stack.


void display( )
{
int i;
if(isEmpty())
{
printf(“stack is empty\n”);
return;
}
printf(“stack elements: ”);
for(i=top; i>=0; i--)
printf(“%d\n”, stack_arr(i));
printf(“\n”);
}
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Disadvantages of array implementation

• It is not dynamic i.e., it doesn’t grow and shrink depending on needs at


runtime.

• The total size of the stack must be defined beforehand.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Stacks implementation using a Linked List:
• When the size of the stack is not known in advance, it is better to
implement it as a linked list.

• The main advantage of using a linked list over arrays is that it is possible to
implement a stack that can shrink or grow as much as needed.

struct node
{
int info;
struct node *link;
};
struct node *top = NULL;

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


(a) Empty Stack (b) Push 5 (c) Push 10
Top is NULL Top Top

5 10 5

(d) Push 15 (e) Pop


Top Top 15

15 10 5 10 5

(f) Pop (g) Pop


Top 10 Top 5

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Push Operation: The function push( ) would be similar to the function
addatbeg( ) of single linked list.
void push(int item)
{
struct node *tmp;
tmp = (struct node*)malloc(sizeof(struct node));
tmp -> info = item;
if(tmp = = NULL) /*Memory is full*/
{
printf(“Stack Overflow\n”);
return;
}
tmp->link = top;
top = tmp;
}

(b) Push 5 (c) Push 10


Top Top

5 10 5

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Pop Operation: Pop delete the first element of the linked list. If the stack is
empty, then it is said to be an Underflow condition.

int pop( )
{ (e) Pop
struct node * tmp; Top 15
int item;
if(isEmpty())
{ 10 5
printf(“stack underflow”);
return;
} (f) Pop
tmp = top; Top 10
item = tmp->info;
top = top->1ink;
free(tmp);
5
return item;
}

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Peek Operation: return the top element of the stack.
Algorithm for Peek Operation int peek( )
{
Step 1: IF TOP == NULL, then if(isEmpty())
PRINT “STACK IS EMPTY”
{
Go TO Step 3
[END OF IF] printf(“stack underflow”);
Step 2: RETURN STACK[TOP] return;
Step 3: END }
return top->info;
}

isEmpty( ) Operation int isEmpty( )


{
if(top == NULL)
return 1;
else
return 0;
}

isFull( ) Operation: This operation is not required.


Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
display( ): print all elements of the stack.
void display( )
{
struct node *ptr;
ptr = top;
if(isEmpty())
{
printf(“stack is empty\n”);
return;
}
printf(“stack elements: ”);
while(ptr!=NULL)
{
printf(“%d\n”, ptr->info);
ptr = ptr->link;
}
}

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Multiple Stack
When we implemented a stack using an array, we had seen that the size of
the array must be known in advance. If the stack is allocated less space, then
frequent OVERFLOW conditions will be encountered.

In case, we allocate a large amount of space for the stack, it will result in
sheer wastage of memory. Thus, there lies a tradeoff between the frequency
of overflows and the space allocated.

So a better solution to deal with this problem is to have multiple stacks or to


have more than one stack in the same array of sufficient size.

0 1 2 3 4 ………………………………. n-4 n-3 n-2 n-1

Stack A Stack B

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


When an array of STACK[n] is used to represent two stacks, say Stack A
and Stack B. Then the value of n is such that the combined size of both the
Stack[A] and Stack[B] will never exceed n. Stack[A] will grow from left to
right, whereas Stack[B] will grow in opposite direction i.e. right to left.

#define MAX 50
int stack[MAX];
int topA = -1;
int topB = MAX;

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


#include <stdio.h>
#include <malloc.h>
#define MAX 10
int stack[MAX], topA = -1, topB = MAX;
int main()
{ case 5:
int option, val; printf("\n The contents of Stack A are :\n");
do display_stackA();
{ break;
printf("\n -----Menu----- "); case 6:
printf("\n 1. PUSH a element into Stack A"); printf("\n The contents of Stack B are :\n");
printf("\n 2. PUSH a element into Stack B"); display_stackB();
printf("\n 3. POP a element from Stack A"); break;
printf("\n 4. POP a element from Stack B"); }
printf("\n 5. Display the Stack A"); }while(option != 7);
printf("\n 6. Display the Stack B"); return 0;
printf("\n 7. Exit"); }
printf("\n Enter your choice");
scanf("%d",&option);
switch(option)
{
case 1:
printf("\n Enter the value to push on stack A :");
scanf("%d",&val);
pushA(val);
break;
case 2:
printf("\n Enter the value to push on stack B:");
scanf("%d", &val);
pushB(val);
break;
case 3:
if(val != -999)
printf("\n The value popped from Stack A = %d", val);
break;
case 4:
if(val != -999)
printf("\n The value popped from Stack B = %d",val);
break;

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


void pushA(int val) void pushB(int val)
{ {
if(topA == topB-1) if(topB-1 == topA)
printf("\n Overflow"); printf("\n Overflow");
else else
{ {
topA+=1; topB-=1;
stack[topA] = val; stack[topB] = val;
} }
} }

int popA() int popB()


{ {
int val; int val;
if(topA == -1) if(topB == MAX)
{ {
printf("\n Underflow"); printf("\n Underflow");
val = -999; val = -999;
} }
else else
{ {
val = stack[topA]; val = stack[topB];
topA--; topB++;
} }
return val; return val;
} }

void display_stackA() void display_stackB()


{ {
int i; int i;
if(topA == -1) if(topB == MAX)
printf("\n Stack A is empty"); printf("\n Stack B is Empty");
else else
{ {
for(i = topA; i >= 0; i--) for(i = topB; i < MAX;i++)
printf("\t %d", stack[i]); printf("\t %d",stack[i]);
} }
} }
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
Applications of Stacks

• Reversal of string or list

• Function calls

• Recursion

• Checking the validity of an expression containing nested parentheses

• Conversion of an infix expression into a postfix expression

• Evaluation of a postfix expression

• Conversion of an infix expression into a prefix expression

• Evaluation of a postfix expression

• Tower of Hanoi

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Reversal of string
We can reverse a string by pushing each character of the string on the stack.
After the whole string is pushed on the stack, we can start popping the
characters from the stack and get the reversed string.

We have pushed the string “SPOT” on the stack and we get the reversed
string “TOPS”.

T O P S

T
O O O
P P P P P
S S S S S S S

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Program of reversing a string using stack
#include<studio.h> void push(int item)
#include< string.h> {
#include<stdlib.h> if(isFull())
{
#define MAX 20
printf(“stack overflow”);
int top = -1;
return;
char stack[MAX]; }
char pop( ); top = top + 1;
void push (char); stack_arr[top] = item;
main() }
{ char str(20);
unsigned int i; char pop( )
printf(“Enter the string”); {
gets(str); int item;
for(i =0; i<starlen(str); i++) if(top = = -1)
push(str(i); {
for(i =0; i<starlen(str); i++) printf(“stack underflow”);
str[i] = pop(); return;
printf(“Reversed string is: ”); }
puts(str); item = stack_arr(top);
} top = top-1;
return item;
}

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Checking the validity of an expression containing nested parentheses

• We can use stack to check the validity of an expression that uses nested
parentheses.
• An expression will be valid if it satisfies these two conditions:
– The total number of left parentheses should be equal to the total number of
right parentheses in the expression.
– For every right parentheses there should be a left parentheses of the same type.

• [A-B*(C+D)) Invalid
• (1+5} Invalid
• [5+4*(9-2)] Valid
• [A/(B+C)*D] Valid

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


Procedure:
1. Initially take an empty stack.
2. Scan the symbols of expression from left to right
3. If a symbol is a left parenthesis then push it on the stack
4. If a symbol is a right parenthesis
if the stack is empty
Invalid: right parentheses are more than left parenthesis
else
pop an element from the stack.
if the popped parenthesis does not match the parentheses being scanned.
Invalid: Mismatched parenthesis.
5. After scanning all the symbols
If the stack is empty
Valid: Balanced parenthesis
else
invalid: left parentheses more than right parentheses.

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India


[A/(B-C)*D] [A/(B-C)*D] [A/(B-C)*D] [A/(B-C)*D]
Symbol Stack Symbol Stack Symbol Stack Symbol Stack

[ A / (

(
[ [ [ [

[A/(B-C)*D] [A/(B-C)*D] [A/(B-C)*D] [A/(B-C)*D]


Symbol Stack Symbol Stack Symbol Stack Symbol Stack

B A- C )

( ( (
[ [ [ [

[A/(B-C)*D] [A/(B-C)*D] [A/(B-C)*D]


Symbol Stack Symbol Stack Symbol Stack

* D ]

[ [
#include <stdio.h> int check(char exp[ ])
#define MAX 30 {
int stack[MAX], top = -1; int I;
void push(char); char temp;
char pop(); for(i=0; i<strlen(exp); i++)
int match(char a, char b); {
main() if(exp[i] ==‘(‘ || exp[i] ==‘{‘ || exp[i] == ‘[‘)
{ push(exp[i]);
int valid; if(exp[i] ==‘)‘ || exp[i] ==‘}‘ || exp[i] == ‘]‘)
char exp[MAX]; if(top = = -1)
printf(“Enter an algebraic expression); {
gets(exp); printf(“Right parentheses are more than left\n)”
valid = check(exp); return 0;
if(valid = = 1) }
printf(“Valid expression”); else
else {
printf(“Invalid expression”); temp = pop( );
} if(!match(temp, exp[i]))
{
printf(“Mismatched parentheses are :”);
printf(“%c and %c\n”, temp, exp[i]);
return 0;
int match(char a, char b) }
{ }
if(a ==‘[‘ && b == ‘]’) }
return 1; if(top = -1)
if(a ==‘{‘ && b == ‘}’) {
return 1; printf(“Balanced Parentheses\n”);
if(a ==‘(‘ && b == ‘)’) return 1;
return 1; }
return 0; else
} {
printf(“left parentheses are more than right parentheses\n”);
return 0;
}
}

Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India

You might also like