0% found this document useful (0 votes)
67 views60 pages

Stack Data Structure Overview

Data structure and algorithm

Uploaded by

arvind22cse15
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)
67 views60 pages

Stack Data Structure Overview

Data structure and algorithm

Uploaded by

arvind22cse15
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

Stacks

Definition:
Stack is an linear data structure in which elements are inserted or
deleted at only one end called the top of the stack.

■ This means, the elements are removed from a stack in the reverse
order of which they were inserted into the stack.

■ Since last inserted element is to be removed first, the stack is also


known as Last In First Out( LIFO ) list.

1
Stack Operations

Basic operations associated with stack:

1. Push : term used for inserting an element into the top of the
stack

2. Pop : term used to delete an element from the top of the stack

Overflow: Check whether the stack is full


Underflow: Check whether the stack is full
Array Representation of Stacks
■ Stacks may be represented in computer usually by means of linear array
or a one–way list.

■ Unless otherwise stated, stacks are represented by a linear array.

■ Let S be the stack: S = (a0, a1, a2, a3, … , an–1 )

■ Here, a0 is the Bottom Element of the Stack or Base Element of the


Stack. The index 0 is Bottom of the stack or Base of the Stack.

■ an–1 is Top Element of the stack. The index n–1 is top of the stack.
■ The element ai is on top of the element ai–1 where 0 <= i < n.

■ The restriction on the stack imply that : If the Elements A, B, C,


D, and E are inserted in the same order (i.e., E is the top element),
then the Element E is to be removed (or popped ) first from the
stack.

4
ILLUSTRATION OF THE STACK

E □Top
D □Top D D □Top
C □Top C C C
B □Top B B B B
A □Top A A A A A

After After After After After After


PUSH PUSH PUSH PUSH PUSH POP E
A B C D E
Stack operations
1. Push :
void push ()
{
if(top==maxsize-1)
{
printf(“Stack overflow\n”);
}
else
{
printf(“Enter the element to be pushed”);
scanf(“%d”, & ele);
top++;
stack[top]=ele;
}
}
6
2. Pop:

void pop()
{
if(top==-1)
printf(“Stack Underflow”);
else
{
printf(“Popped element is %d”,stack[top]);
top --;
}
}

7
Stack ADT

ADT Stack is
Objects: It is a finite ordered list with zero or more elements.
Functions:
For all stack Є Stack, item Є element, maxStackSize Є positive integer.
Stack CreateS(maxStackSize) ::= Creates an empty stack whose
maximum size is maxStackSize.
Boolean If(number of elements in stack ==
IsFull(stack,maxStackSize) ::= maxStackSize)
return TRUE
Else return FALSE
Stack ADT

Stack Push(stack, item) ::= If(IsFull(stack)) stackfull


Else insert item into top of the stack and return.
Boolean IsEmpty(stack) ::= If no elements in the stack
return TRUE
Else return FALSE
Element Pop(stack) If(IsEmpty(stack) ) stackempty
Else remove and return the element at the top
of the stack.
STACK ADT FUNCTIONS

10
1) CreateS(maxStackSize) Function – creating
a stack using structure
Stack createS(maxStackSize) ::=
#define MAX_STACK_SIZE 100
typedef struct
{
int key;
/* other fields */
} element;
element stack[MAX_STACK_SIZE];
int top = -1;
IsEmpty and IsFull Functions

Boolean IsEmpty(Stack)::=
If(top < 0) return TRUE
Else return FALSE

Boolean IsFull(Stack)::=
If(top >= MAX_STACK_SIZE–1)
return TRUE;
Else return FALSE
2) PUSH FUNCTION

void push(element item)


{
if(top = = MAX_STACK_SIZE – 1)
print OVERFLOW and return;
else stack[++top] = item;
}
3) POP FUNCTION
Element pop()
{ /* delete and return the top element
from the stack*/
if(top == -1)
return stackEmpty();
else return stack[top--];
}
Stack Using Dynamic Arrays
■ In Array Representation of the stack, the MAX_STACK_SIZE
must be known at compile time. i.e we need to know how
large the stack will become

■ We can overcome this shortcoming by using dynamically


allocated array for the elements and then increasing the size of
this array as needed.
CreateS() Function

Stack CreateS() ::=


typedef struct
{
int key;
/* other fields */
} element;
element *stack;
stack = (element *) malloc(sizeof(*stack));
int capacity = 1;
int top = -1;
■ Code for stack full need to be modified. We need to check
with capacity instaed of MAX_STACK_SIZE.

■ In stackfull, it must attempt to increase the capacity of the


array stack so that we can add an additional element to the
stack.

■ In array doubling, we double the array capacity whenever it


becomes necessary to increase the capacity of an array.

22
StackFull() Function

void stackFull()
{
REALLOC(stack, 2*capacity*sizeof(*stack));
capacity *= 2;
}
Stack Applications
■ Polish notation

■ Infix to postfix conversion

■ Evaluation of postfix expression


■ In an arithmetic expression that involves binary operations, the
level of precedence is:

Highest : Exponentiation
Next highest : Multiplication and division
lowest : Addition and subtraction

■ The operations on the same level of precedence is evaluated


from left to right

25
Expression Notation
■ Infix Notation : The notation in which the operator is placed
between its two operands.
Eg: A+B C*D

■ Postfix Notation (or Reverse Polish Notation or suffix notation) :


the notation in which the operator is placed after its two operands.
Eg: AB+ CD*

■ Prefix Notation (or Polish Notation) : The notation in which the


operator is placed before its two operands.
Eg: +AB *CD
Polish Notation
■Example: Consider the Infix Expression: (A+B)*C
Obtain the polish notation for the given expression
Evaluation:
(A+B)*C = [+AB]*C = * +ABC
The POLISH NOTATION is: *+ABC

■ The fundamental property of the polish notation is that the order in


which the operations are to be performed is completely determined
by the positions of the operators and the operands in the expression.

■ Parenthesis is not needed when writing expressions in polish


notation
Exercise to the students
■ Represent the following Infix Expression in Polish Notation
(Prefix Notation) and in reverse Polish Notation (Postfix
Notation):

1. (A+B)/(C-D)
2. A+B*C
3. A+B/C-D
4. 2^3+5*2^3-6/3
■ The computer usually evaluates an arithmetic expression
written in infix notation in two steps:

■ First it converts the expression to postfix notation and then it


evaluates the postfix expression

■ In each step, stack is the tool used to accomplish the task.

29
Evaluation of postfix expression
■ Consider the Postfix Expression as shown below:
P: 5 6 2 + * 12 4 / –
Add ) to end of P as sentinel to mark end of
expression
Symbol Scanned STACK
5 5
6 5 6
2 5 6 2
+ 5 8
* 40
12 40 12
4 40 1 4
2
/ 40 3
- 37
)
Algorithm for Evaluation of Postfix Expression
This algorithm finds the value of an arithmetic expression P written in
postfix notation.
1.Add a right parenthesis “)”at the end of P.

2.Scan P from left to right and repeat step 3 and 4 for each

element of P until the sentinel “)” is encountered.


3.If an operand is encountered: push it into stack.
4.If an operator is encountered, then :

a) Remove the two top elements of the stack,


where A is the top element and B is the
next to top element.
b) Evaluate= B operator A
q Place the result of (b) back on stack.
[ end of if structure]
[end of step 2 loop]
6.Set VALUE equal to the top element on stack.

7.Exit
Exercise to the Students
Evaluate the following postfix expressions

■ 3 4 5 * 6 / +
■ 4 8 + 6 5 - * 3 2 – 7 9 + * /
■ 5 3 + 2 * 6 9 7 - / -
■ 3 5 + 6 4 - * 4 1 – 2 ^ +
■ 3 1 + 2 ^ 7 4 – 2 * + 5 -
Infix to Postfix Conversion

■ Convert following Infix expression into Postfix.

A + (B * C – (D / E ^ F ) * G) * H
Algorithm: Conversion of Infix expression to postfix

Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression P.

1. Push “(“ onto STACK , and add “)” to the end of Q.


2.Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the
STACK is empty:
3. If an operand is encountered, add it to P
4. If a left parenthesis is encountered, push it onto STACK
5. If an operator is encountered, then:

(a) Repeatedly pop from STACK and add to P each operator (on the top of STACK)
which has the same precedence as or higher precedence than the scanned operator.

(b) add the scanned operator to STACK


[End of if structure]

34
6. If a right parenthesis is encountered, then:

(a) repeatedly pop from STACK and add to P each operator(on the top of STACK)
until a left parenthesis is encountered.
(b) Remove the left parenthesis . [Do not add the left parenthesis to P]

[End of if structure]
[End of step 2 loop]

7. Exit

35
Solution: A + (B * C – (D / E ^ F ) * G) * H

Input Description STACK POSTFIX


Symb
ol
(1) A Since A is the operand, insert this into ( A
postfix expression
(2) + Stack[top] is ‘$’, input symbol is ‘+’ ( + A
Since precedence($) < precedence(+),
push ‘+’
(3) ( Stack[top] is ‘+’, input symbol is ‘(’ ( + ( A
Since precedence(+) < precedence((),
push ‘(’
(4) B Since B is the operand, insert this into ( + ( A B
postfix expression
(5) * Stack[top] is ‘(‘, input symbol is ‘*’ ( + ( * A B
Since precedence(() < precedence(*),
push ‘*’
(6) C Since C is the operand, insert this into ( + ( * A B C
postfix expression
Solution: A + (B * C – (D / E ^ F ) * G) * H

Input Remarks STACK POSTFIX


Symbol
(7) – Stack[top] is ‘*‘, input symbol is ( + ( – A B C *
‘–’. Since precedence(*) >
precedence(–), insert stack[top]
i.e., ‘*’ into postfix.

(8) ( Stack[top] is ‘–‘, input symbol is ( + ( – ( A B C *


‘(’. Since precedence(–) <
precedence((), push ‘(’
(9) D Since D is the operand, insert this ( + ( – ( A B C * D
into postfix expression

(10) / Stack[top] is ‘(‘, input symbol is ‘/’. ( + ( – ( / A B C * D


Since precedence(() <
precedence(/), push ‘/’
Solution: A + (B * C – (D / E ^ F ) * G) * H
Input Remarks STACK POSTFIX
Symbol
(11) E Since E is the operand, ( + ( – ( / A B C * D E
insert this into postfix
expression
(12) ^ Stack[top] is ‘/‘, input ( + ( – ( / ^ A B C * D E
symbol is ‘^’. Since
precedence(/) <
precedence(^), push ‘^’
(13) F Since F is the operand, ( + ( – ( / ^ A B C * D E F
insert this into postfix
expression
(14) ) Since input symbol is ‘)’, ( + ( – A B C * D E F ^ /
pop all the symbols until
stack[top] is ‘(‘ , insert
these symbols into
postfix in the same order
of pop and discard ‘(‘
from the stack[top].
Solution: A + (B * C – (D / E ^ F ) * G) * H

Input Remarks STACK POSTFIX


Symbol
(15) * Stack[top] is ‘–‘, input ( + ( – * A B C * D E F ^ /
symbol is ‘*’. Since
precedence(–) <
precedence(*), push ‘*’
(16) G Since G is the operand, ( + ( – * A B C * D E F ^ / G
insert this into postfix
expression
(17) ) Since input symbol is ‘)’, ( + A B C * D E F ^ / G
pop all the symbols until * -
stack[top] is ‘(‘ , insert
these symbols into
postfix in the same order
of pop and discard ‘(‘
from the stack[top].
Solution: A + (B * C – (D / E ^ F ) * G) * H

Input Remarks STACK POSTFIX


Symbol
(18) * Stack[top] is ‘+‘, input ( + * A B C * D E F
symbol is ‘*’. Since ^ / G * -
precedence(+) <
precedence(*), push ‘*’

(19) H Since G is the operand, ( + * A B C * D E F


insert this into postfix ^ / G * - H
expression
(20) ) Since input symbol is ), A B C * D E F
pop all the symbols from ^ / G * - H *
the stack and insert +
these into postfix in the
same order of pop other
than (
Symbol STACK POSTFIX Expression
Scanned
(1) A ( A
(2) + ( + A
(3) ( ( + ( A
(4) B ( + ( A B
(5) * ( + ( * A B
(6) C ( + ( * A B C
(7) – ( + ( – A B C *
(8) ( ( + ( – ( A B C *
(9) D ( + ( – ( A B C * D
(10) / ( + ( – ( / A B C * D
(11) E ( + ( – ( / A B C * D E
(12) ^ ( + ( – ( / ^ A B C * D E
(13) F ( + ( – ( / ^ A B C * D E F
(14) ) ( + ( – A B C * D E F ^ /
(15) * ( + ( – * A B C * D E F ^ /
(16) G ( + ( – * A B C * D E F ^ / G
(17) ) ( + A B C * D E F ^ / G * -
(18) * ( + * A B C * D E F ^ / G * -
(19) H ( + * A B C * D E F ^ / G * - H
(20) ) A B C * D E F ^ / G * - H * +
Translate the following INFIX Expression to POSTFIX form.

1. 3+4*5/6
2. (A+B)*(C-D)/(X+Y)
3. (4+8)*(6-5)/((3-2)*(7+9))
4. A+(B*C–(D/E^F)+G)*H
5. 6+2^3^2-4*5
6. (A-B)/(D+E)*F
7. (A-B)/((D+E)*F)
8. ((A+B)/D)^((E-F)*G)
9. ((A+B)/D)^(E-F)*G
10. 5+3^2-8/4*3+6
11. 6+2^3+9/3-4*5

42
Recursion:
■ Definition:

■ Applications:
■ Factorial

■ Fibonacci Series

■ GCD

■ Tower of Hanoi

■ Ackerman's function.
Recursion
■ Definition:

The process in which a function calls itself directly or indirectly


is called recursion and the corresponding function is called as
recursive function.

Recursive function must have following two properties:


1) There must be certain arguments called base values for which
the function does not refer to itself.
2) Each time the function does refer to itself, the argument of the
function must be closer to the base value.

44
Factorial Function

Definition:
if n=0, then n! = 1 (Base condition)
if n>0, then n! = n * (n-1)!

Recursive Formula for Factorial is:


n! = n * (n-1)!

Example:
5! = 5 * 4!
= 5 * 4 * 3!
= 5 * 4 * 3 * 2!
= 5 * 4 * 3 * 2 * 1!
=5*4*3*2*1
= 120
Factorial of a Number using Recursion in C
#include <stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter the number whose factorial is to
be found:\n ");
scanf("%d", &n);
printf("Factorial of %d is = %d", n,factorial(n));
return 0;
}
int factorial(int n)
{
if (n ==0)
return 1;
else
return n*factorial(n-1);
}
Fibonacci series using recursive function in C

Formal definition of Fibonacci sequence:

(a) If n=0 or n=1, then Fn = n


(b) If n>1, then Fn = Fn -2+ Fn-1

Fibonacci series: 0 1 1 2 3 5 8 …………


Fibonacci series using recursion

Base Condition:
FIB(0) = 0
FIB(1) = 1

Recursion Formula for nth Fibonacci number is:


FIB(N) = FIB(N-1)+ FIB(N-2)
Fibonacci series using recursive function in C
#include<stdio.h>
int fibonacci(int n);
int main()
{
int n, i;
printf(“Enter the value of n:\n”);
scanf("%d",&n);
if(n==0)
printf(“Enter a valid positive integer\n”);
else
{
printf("Fibonacci series for n = %d is :\n“,n);
for (i = 0; i < n; i++)
{
printf("%d\n", fibonacci(i));
}
}
return 0;
}
int fibonacci(int n)
{
if ( n == 0 ) return 0;
else if ( n == 1 ) return 1;
else return (fibonacci(n-2) + fibonacci(n-1));
}
GCD
Example: Find GCD(9,6)

Iteration Method: (n1%n2)

GCD(9,6) = 9 % 6 = 3
= 6 % 3 = 0
Denominator is the GCD
Hence GCD(9,6) = 3.

Recursive Method: GCD(n2, n1%n2)

GCD(9,6) = GCD(6, 9 % 6) = GCD(6,3)


= GCD(3, 6 % 3) = GCD(3,0)
= 3
GCD

Base Condition:
gcd(n,0) = n

Recursion condition:
gcd(n2, n1%n2)

52
GCD
#include <stdio.h>
int gcd(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
printf("G.C.D of %d and %d is %d”, n1, n2,gcd(n1,n2));
return 0;
}
int gcd(int n1, int n2)
{
if (n2 != 0)
return gcd(n2, n1%n2);
else
return n1;
}
TOWERS OF HANOI
■ Using recursion, we can develop an algorithm to solve a
particular problem.

■ One such problem is Tower of Hanoi.

■ Tower of Hanoi consists of three pegs or towers with n disks


placed on the initial peg one over the other with decreasing
size. The objective of the puzzle(game) is to move the disks
from one peg to another peg using auxiliary peg following
these simple rules:
■ Only one disk can be moved at a time. Specifically, Only the
top disk on any peg may be moved to any other peg
■ No larger disk can be placed on top of the smaller disk.
Initial setup of towers of hanoi

55
56
Example: Take an example with 2 disks: Disk 1 on top of
Disk 2 at peg A. The target is to move both these disks to
peg C using auxiliary peg B.

1. Move Disk 1 from peg A to peg B.


2. Move disk 2 from peg A to peg C
3.Move disk 1 from peg B to peg C.
This solution takes 3 steps.
Tower of hanoi with three Disks

A B C A B C A B C
Initial (1) (2)

A B C A B C A B C
(3) (4) (5)

A B C A B C
(6) (7)
The recursive solution for n=3 has 7 moves.

In general,

the recursive solution requires 2n-1 moves for n disks

59
Solution to towers of hanoi problem
We use technique of recursion to develop a solution to the
problem.

The solution is :

■ When n=1, move the disk from begin to end

■ When n>1, solution is reduced to the solution of the following


three sub problems.
Step 1 − Move n-1 disks from begin to aux
Step 2 − Move nth disk from begin to end
Step 3 − Move n-1 disks from aux to end
General notation:
TOWER(N,BEG,AUX,END)

When n=1, the solution is


TOWER(1,BEG,AUX,END) with the instruction BEG→ END

When n>1, the solution is


1. TOWER(N-1, BEG,END,AUX)

2. TOWER(1,BEG,AUX,END) OR BEG→ END


3. TOWER(N-1, AUX,BEG,END)

61
Algorithm
TOWER(N,BEG,AUX,END)
1. If N=1, then :

a) Write: BEG → END


b)Return

[End of if ]

2.[Move N-1 disks from peg BEG to AUX]


Call TOWER(N-1, BEG, END, AUX)
3.Write: BEG → END
4.[Move N-1 disks from peg AUX to END]
Call TOWER(N-1, AUX, BEG, END)
5.Return
C Program for tower of hanoi

#include <stdio.h>
void towers(int, char, char, char);
int main()
{
int num;
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the
Tower of Hanoi are :\n");
towers(num, 'A', ‘B', ‘C');
return 0;
}
void towers(int N, char BEG, char AUX, char END)
{
if (N == 1)
{
printf("\n Move disk 1 from peg %c to peg
%c", BEG, END);
return;
}
towers(N - 1, BEG, END, AUX);
printf("\n Move disk %d from peg %c to peg %c",
n,BEG, END);
towers(N - 1, AUX, BEG, END);
}

64
OUTPUT OF THE PROGRAM

Enter the number of disks : 3


The sequence of moves involved in the Tower of
Hanoi are :

Move disk 1 from peg A to peg C


Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

You might also like