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

Stack

The document provides a comprehensive overview of stacks as an Abstract Data Type (ADT), including operations like PUSH and POP, and conditions for overflow and underflow. It also discusses the conversion between infix, postfix, and prefix notations, along with algorithms for evaluating postfix expressions and converting infix to postfix. Additionally, it covers recursion with examples such as factorial and Fibonacci sequences.

Uploaded by

dipeshcrestra7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Stack

The document provides a comprehensive overview of stacks as an Abstract Data Type (ADT), including operations like PUSH and POP, and conditions for overflow and underflow. It also discusses the conversion between infix, postfix, and prefix notations, along with algorithms for evaluating postfix expressions and converting infix to postfix. Additionally, it covers recursion with examples such as factorial and Fibonacci sequences.

Uploaded by

dipeshcrestra7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 61

a.

Concept and Definition


• Primitive Operations
• Stack as an ADT
• Implementing PUSH and POP operation
• Testing for overflow and underflow conditions
b. The Infix, Postfix and Prefix
• Concept and Definition
• Evaluating the postfix operation
• Converting from infix to postfix
c. Recursion
• Concept and Definition
• Implementation of:
 Multiplication of Natural Numbers
 Factorial
 Fibonacci Sequences
 The Tower of Hanoi

Prepared by Ramesh singh Saud 1


 A stack is an ordered collection of items into which
new items may be inserted and from which items
may be deleted at only one end, called the top of
the stack.
 Unlike array, the definition of the stack provides for
the insertion and deletion of items, so that a stack is
a dynamic, constantly changing object.
 For insertion, new items are put on the top of the
stack in which case the top of the stack moves
upward to correspond to the new highest element.
 For deletion, items which are at the top of the stack
are removed in which case the top of the stack
moves downward to correspond to the new highest
element.
 Since items are inserted and deleted in this manner,
a stack is also called a last-in, first-out (LIFO) list.
Prepared by Ramesh singh Saud 2
Prepared by Ramesh singh Saud 3
 When an item is added to a stack, it is
pushed onto the stack, and when an item is
removed, it is popped from the stack.
 Given a stack s, and an item i, performing
the operation push(s, i) adds the item i to
the top of stack s. Similarly, the operation
pop(s) removes the element at the top of s
and returns it as a function value. Thus the
assignment operation i=pop(s); removes
the element at the top of s and assigns its
value to i.
 Note: Because of the push operation which
adds elements to a stack, a stack is also
called a pushdown list.
Prepared by Ramesh singh Saud 4
 There is no upper bound on the
number of items that may be kept in
a stack, i.e. the operation push is
applicable to any stack, however if a
stack contains a single element and
the stack is popped, the resulting
stack contains no items, called
empty stack, and the operation pop
cannot be applied to empty stack.
 The operation empty(s) determines
whether or not a stack s is empty. If
the stack is empty, empty(s) returns
the value TRUE; otherwise it returns
the value FALSE.
Prepared by Ramesh singh Saud 5
 Another operation that can be
performed on a stack is to determine
what the top item on a stack is
without removing it.
 The operation stacktop(s) returns
the top element of stack s.
 Similar to operation pop, stacktop is
not defined for an empty stack.
 The result of an illegal attempt to pop
or access an item from an empty
stack is called underflow.
 Underflow can be avoided by
ensuring that empty(s) is FALSE
before attempting the operation
pop(s) or stacktop(s).
Prepared by Ramesh singh Saud 6
 Let eltype denote the type of the stack element with STACK(eltype) being the
parameterized stack type with eltype.

/* value definition */
abstract typedef <<eltype>> STACK(eltype);

/* operator definition */
abstract empty(s)
STACK(eltype) s;
postcondition empty == (len(s) == 0);

abstract eltype pop(s)


STACK(eltype) s;
precondition empty(s) == FALSE;
postcondition pop == first(s1);
s == sub(s1, 1, len(s1-1));

abstract push(s, elt)


STACK(eltype) s;
eltype elt;
postcondition s == <elt>+s1;

Prepared by Ramesh singh Saud 7


 An array and a stack are two completely different
things (An array is a collection of items and has a
finite size whereas the size of a stack is dynamic
and changes as elements are pushed or popped).
 However an array can be used as a home for a
stack by declaring an array that is large enough
for the maximum size of the stack so that during
program execution, the stack can grow and
shrink within the space reserved for it.
 One end of the array is the fixed bottom of the
stack, while the top of the stack constantly shifts
as items are pushed and popped.
 Therefore, a field that keeps track of the current
position of the top of the stack is needed at each
point during program execution.
Prepared by Ramesh singh Saud 8
 Thus, a stack in C can be declared as a structure
containing two members: an array to hold the
elements of the stack, and an integer to
indicate the position of the current stack top
within the array.
#define STACKSIZE 100
struct stack
{
int items[STACKSIZE];
int top;
};

An actual stack can now be declared as:


struct stack s;
Prepared by Ramesh singh Saud 9
 Note:
 If the value of s.top is 4, there are five elements on the
stack: s.items[0], s.items[1], s.items[2], s.items[3], and
s.items[4].
 When the stack is popped, the value of s.top is changed to
3 to indicate that there are now only 4 elements on the
stack and that s.items[3] is the top element.
 When a new item is pushed onto the stack, the value of
s.top must be increased by 1 i.e. s.top becomes 5 and the
new item is inserted into s.items[5].

Prepared by Ramesh singh Saud 10


 To initialize the stack s to the empty
state, we should initialize s.top to -1.
 Also to determine whether or not a stack
is empty, the condition s.top==-1 should
be tested.

Prepared by Ramesh singh Saud 11


 There is possibility of underflow in
implementing the pop operation, since
the user may inadvertently attempt to
pop an element from an empty stack.
 To avoid such condition, we should create
a function pop that performs the
following three actions:
1. If the stack is empty, print a warning message
and halt execution.
2. Remove the top element from the stack.
3. Return this element to the calling program.

Prepared by Ramesh singh Saud 12


//C code to implement pop
int pop(struct stack *s)
{
if(s->top == -1)
{
printf("\n STACK UNDERFLOW");
exit(1);
}
return (s->items[s->top--]);
/*top item is returned and after that top is
decremented*/
}

Prepared by Ramesh singh Saud 13


 A stack is a dynamic data structure that is
constantly allowed to grow and shrink and
thus change its size whereas an array has a
predetermined size.
 The array implementation of stack’s push
operation may thus sometimes outgrow the
array size that was set aside to contain the
stack.
 This situation occurs when the array is full, i.e.
when the stack contains as many elements as
the array and an attempt is made to push yet
another element onto the stack. The result of
such an attempt is called an overflow.
Prepared by Ramesh singh Saud 14
//C code to implement push
void push(struct stack *s, int x)
{
if(s->top == STACKSIZE-1)
{
printf("\n STACK OVERFLOW");
exit(1);
}
else
{
printf("\n Enter value you want to push:");
scanf("%d", &x);
++(s->top);
s->items[s->top] = x;
}
}
Prepared by Ramesh singh Saud 15
 Define Stack as an ADT. Explain the
condition that is to be checked for Push
and Pop operations when Stack is
implemented using array?

Prepared by Ramesh singh Saud 16


 Write a menu program to demonstrate
the simulation of stack operations in
array implementation.

Prepared by Ramesh singh Saud 17


Prepared by Ramesh singh Saud 18
Prepared by Ramesh singh Saud 19
 Consider the sum of A and B. Generally,
we apply the operator “+” to the
operands A and B and write the sum as
the expression A+B. This particular
representation is called infix.
 There are two alternate notations for
expressing the sum of A and B using the
symbols A, B, and +. These are:
+AB (prefix)
AB+ (postfix)
Prepared by Ramesh singh Saud 20
 The prefixes “pre-”, “post-” and “in-”
refer to the relative position of the
operator with respect to the two
operands.
 In prefix notation the operator precedes
the two operands, in postfix notation the
operator follows the two operands, and in
infix notation the operator is between the
two operands.

Prepared by Ramesh singh Saud 21


 The operations involving operator with
the highest precedence is converted first
and then a portion of that expression is
treated as a single operand.
 The precedence of operators is:
 Parentheses ()
 Exponentiation $
 Multiplication/division *, /
 Addition/subtraction +, -

Prepared by Ramesh singh Saud 22


 When unparenthesized operators of
the same precedence are scanned, the
order is assumed to be from left to right
except in the case of exponentiation,
where the order is assumed to be from
right to left.
 Thus A+B+C means (A+B)+C, whereas
A$B$C means A$(B$C).

Prepared by Ramesh singh Saud 23


a. A+B
b. A+B-C
c. (A+B)*(C-D)
d. A$B*C-D+E/F/(G+H)
e. ((A+B)*C-(D-E))$(F+G)
f. A-B/(C*D$E)

Prepared by Ramesh singh Saud 24


 Algorithm
1. The postfix string is scanned left-to-right one character at
a time.
2. Whenever an operand is read, it is pushed onto the
opndstack.
3. When an operator is read, the top two operands from the
stack is popped out into op2 and op1, the operator is
applied in between the two operands (op1 operator op2)
and the result of the operation is pushed back onto the
opndstack (so that it will be available for use as an
operand of the next operator).
4. Pop and display opndstack.

Prepared by Ramesh singh Saud 25


postfix op1 op2 result opndstack
6 6
2 6,2
3 6,2,3
+ 2 3 5 6,5
- 6 5 1 1
3 6 5 1 1,3
8 6 5 1 1,3,8
2 6 5 1 1,3,8,2
/ 8 2 4 1,3,4
+ 3 4 7 1,7
* 1 7 7 7
2 1 7 7 7,2
$ 7 2 49 49
3 7 2 49 49,3
+ 49 3 52 52
Prepared by Ramesh singh Saud 26
#include<math.h>
#include<string.h>
#define STACKSIZE 100
void push(struct opndstack *,int);
int pop(struct opndstack *);

struct opndstack
{
int items[STACKSIZE];
int top;
};
Prepared by Ramesh singh Saud 27
void main()
{
char postfix[STACKSIZE], ch;
int i, l;
int x;
struct opndstack s;
int op1,op2;
int value;
int result;
s.top=-1;
clrscr();
printf("Enter a valid postfix:");
gets(postfix);
l=strlen(postfix);
for(i=0;i<=l-1;i++)
{
if(isdigit(postfix[i]))
{
x=postfix[i];
push(&s,(int)(x-'0'));
}
Prepared by Ramesh singh Saud 28
Prepared by Ramesh singh Saud 29
Prepared by Ramesh singh Saud 30
 Algorithm
1. The infix expression is scanned from left to right one
character at a time.
2. If left parentheses i.e. ‘(’ is encountered, push it to
opstack .
3. If operand is encountered, add operand to postfix string.
4. If operator is encountered, push operator into opstack if the
opstack is empty or if the precedence of the current
operator on top of opstack is smaller than the currently
scanned operator.
5. Whenever right parentheses i.e. ‘)’ is encountered, pop
opstack until a matching left parentheses is found and
cancel both.
6. While opstack is not empty, pop operators from opstack
and add operators to postfix string.
7. Display postfix string.

Prepared by Ramesh singh Saud 31


infix postfix opstack

A A

+ A +

B AB +

* AB +, *
C ABC +, *

ABC* +

ABC*+

Prepared by Ramesh singh Saud 32


infix postfix opstack

( (

A A (

+ A (, +

B AB (, +
) AB+

* AB+ *

C AB+C *

AB+C*

Prepared by Ramesh singh Saud 33


Prepared by Ramesh singh Saud 34
infix postfix opstack
( (
( (, (
A A (, (
- A (, (, -
( A (, (, -, (
B AB (, (, -, (
+ AB (, (, -, (, +
C ABC (, (, -, (, +
) ABC+ (, (, -
) ABC+- (
* ABC+- (, *
D ABC+-D (, *
) ABC+-D*
$ ABC+-D* $
( ABC+-D* $, (
E ABC+-D*E $, (
+ ABC+-D*E $, (, +
F ABC+-D*EF $, (, +
) ABC+-D*EF+ $
ABC+-D*EF+$
Prepared by Ramesh singh Saud 35
 How can you convert from infix to postfix
notation.

Prepared by Ramesh singh Saud 36


 Infix notation is easy to read for humans,
whereas pre-/postfix notation is easier to
parse for a machine.
 The big advantage in pre-/postfix notation is
that there never arise any questions like
operator precedence.
 The expression is evaluated from left-to-
right using postfix and whenever operands
are encountered it is pushed onto the stack
whereas whenever operator is encountered,
two of the operands are popped, the
operator is applied in between the two
operands and the result is pushed again in
the stack.
Prepared by Ramesh singh Saud 37
 Example:
 Using infix try to parse A+B*C
 Push operand A onto stack
 Save operator + somewhere
 Push operand B onto stack
 Now what??? Add A and B or save another operator *
 Problem: Need to know precedence rules and need to look ahead.
 Using postfix try to parse ABC*+
 Push operand A onto stack
 Push operand B onto stack
 Push operand C onto stack
 Whenever operator is encountered, pop the two operands from stack,
perform the binary operation and push the result onto the stack. Thus at
first C and B are popped, then they are multiplied and then the result is
pushed onto the stack.
 Now another operator is encountered, and the above process is
repeated again.

Prepared by Ramesh singh Saud 38


 Recursion in computer science is a
problem-solving method where the
solution to a problem depends on solutions
to smaller instances of the same problem.
 This approach can be applied to many
types of problems, and is one of the
central ideas of computer science.
 Most computer programming languages
support recursion by allowing a function to
call itself within the program text.

Prepared by Ramesh singh Saud 39


 When a function calls itself directly or
indirectly, it is called recursive function.
 Two types:

(i) Direct Recursion (ii) Indirect Recursion


 E.g.

void main()
{
printf(“This is direct recursion. Goes
infinite\n");

main();
}
Prepared by Ramesh singh Saud 40
 E.g.
void printline();
void main()
{
printf(“ This is not direct recursion.\n");
printline();
}
void printline()
{
printf("Indirect Recursion. Goes
Infinite\n");
main();
}
Prepared by Ramesh singh Saud 41
 To solve a problem using recursive
method, two conditions must be satisfied:
1) Problem should be written or defined in
terms of its previous result.
2) Problem statement must include a
terminating condition, otherwise the
function will never terminate. This means
that there must be an if statement
somewhere in the recursive function to
force the function to return without the
recursive call being executed.
Prepared by Ramesh singh Saud 42
Recursion Iteration
1. A function is called from the definition1. Loops are used to perform repeated
of the same function to do repeated task. task.
2. Recursion is a top-down approach to2. Iteration is a bottom-up approach: it
problem solving: it divides the problem begins from what is known and from
into pieces. this it constructs the solution step-by-
E.g. Computing factorial of a number: step.
long int factorial(int n) E.g. Computing factorial of a number:
{ int fact=1;
if(n==0) return 1; for(i=1;i<=n;i++)
else {
return (n*factorial(n-1)); fact=fact*i;
} }
3. Problem to be solved is defined in terms3. It is not necessary to define a problem
of its previous result to solve a problem in terms of its previous result to solve
using recursion. using iteration. For e.g. “Display your
name 1000 times”
4. In recursion, a function calls to itself 4. In iteration, a function does not call to
until some condition is satisfied. itself.
5. All problems cannot be solved using5. All problems can be solved using
recursion. iteration.
6. Recursion utilizes stack. 6. Iteration
Prepared by Ramesh singh Saud does not utilize stack. 43
 Recursion uses stack to keep the successive generations of
local variables and parameters of the function in its
corresponding calls.
 This stack is maintained by the C system and is invisible to
the user (programmer).
 Each time a recursive function is entered, a new allocation of
its variables is pushed on top of the stack.
 Any reference to a local variable or parameter is through the
current top of the stack.
 When the function returns, the stack is popped, the top
allocation is freed, and the previous allocation becomes the
current stack top to be used for referencing local variables.
 Each time a recursive function returns, it returns to the point
immediately following the point from which it was called.

Prepared by Ramesh singh Saud 44


long int factorial(int n)
{
if(n==0)
return 1;
else
return (n*factorial(n-1));
}
void main()
{
int number;
long int x;
clrscr();
printf("Enter a number whose factorial is needed:\t");
scanf("%d", &number);
x=factorial(number);
printf("\n The factorial is:%ld", x);
getch();
}

Prepared by Ramesh singh Saud 45


While calculating the factorial
of n=5, the else part gets
executed and the value
5*factorial(4) is pushed onto the
stack. Then the factorial
function gets called again
recursively with n=4 and
4*factorial(3) is executed and is
pushed onto the stack. This
process goes on like this. When
factorial(1) becomes
1*factorial(0) the factorial
function is called again with
n=0. When n becomes 0, the
function returns 1 and after this
the recursive function starts to
return in a last-in, first-out
manner. The recursive function
returns successive values to the
point from which it was called
in the stack so that the final
value returned is 5*24=120.
Prepared by Ramesh singh Saud 46
 Determine what the following recursive C
function computes. Write an iterative
function to accomplish the same purpose.
int func(int n)
{
if(n==0)
return (0);
return (n + func(n-1));
} /* end func */

Prepared by Ramesh singh Saud 47


 The recursive function computes the sum of
integers from 0 to n where n is the input to the
function.
 For calculating the sum of integers from 0 to n
(with say n=5), the recursive function computes
as:
 With n=5, the else part gets executed and the value
5+func(4) is pushed onto the recursive stack. Then the
func function is called again recursively with n=4 and
4+func(3) is executed and is pushed onto the stack.
This process goes on like this. When func(1) becomes
1+func(0), the func function is called again with n=0.
When n becomes 0, the func function returns 0 and
after this the recursive function starts to return in a
last-in, first-out manner. The recursive function
returns successive values to the point from which it
was called in the stack so that the final value returned
is 5+10=15.
Prepared by Ramesh singh Saud 48
Iterative
Function
int func(int n)
{
int sum=0;
int i;
for(i=0;i<=n;i
++)
sum =
sum+i;
Prepared by Ramesh singh Saud
return sum; 49
 What do you mean by recursion? Explain
the implementation of factorial and
fibonacci sequences with example.

Prepared by Ramesh singh Saud 50


//The fibonacci sequence is: 1,1,2,3,5,8,13,…
//The following program computes the nth Fibonacci
number
int fibo(int n)
{
if(n<=1)
return n;
else
return (fibo(n-1)+fibo(n-2));
}

void main()
{
int pos;
int x;
printf("Enter the position of the nth Fibonacci number:");
scanf("%d", &pos);
x=fibo(pos);
printf("\n The %dth Fibonacci number is:%d", pos, x);
}

Prepared by Ramesh singh Saud 51


int mult(int a, int b)
{
if(b==0)
return 0;
else
return (a+mult(a,--b));
}
void main()
{
int m, n;
int x;
clrscr();
printf("Enter two numbers you want to multiply:");
scanf("%d %d", &m, &n);
x=mult(m, n);
printf("%d*%d=%d", m, n, x);
getch();
}

Prepared by Ramesh singh Saud 52


 There are 3 pegs A, B and C.
 Five disks (say) of different diameters are placed on peg A so that a
larger disk is always below a smaller disk.
 The aim is to move the five disks to peg C, using peg B as auxiliary.
 Only the top disk on any peg may be moved to any other peg, and a
larger disk may never rest on a smaller one.

Prepared by Ramesh singh Saud 53


 The puzzle was first publicized by the French mathematician Édouard
Lucas in 1883. There is a legend about an Indian temple which
contains a large room with three time-worn posts in it surrounded by
64 golden disks. Brahmin priests, acting out the command of an
ancient prophecy, have been moving these disks, in accordance with
the rules of the puzzle, since that time. The puzzle is therefore also
known as the “Tower of Brahma” puzzle. According to the legend,
when the last move of the puzzle is completed, the world will end. The
temple is said to be in Hanoi, Vietnam.
 If the legend were true, and if the priests were able to move disks at a
rate of one per second, using the smallest number of moves, it would
take them 264−1 seconds or roughly 585 billion years or
18,446,744,073,709,551,615 turns to finish.
 Solution: The puzzle can be played with any number of disks,
although many toy versions have around seven to nine of them. The
puzzle seems impossible to many novices, yet is solvable with a
simple algorithm. The number of moves required to solve a Tower of
Hanoi puzzle is 2n -1, where n is the number of disks.

Prepared by Ramesh singh Saud 54


 Let us consider the general case of n disks.
 If we can develop a solution to move n-1 disks, then
we can formulate a recursive solution to move all n
disks.
 In the specific case of 5 disks, suppose that we can move 4
disks from peg A to peg C, using peg B as auxiliary.
 This implies that we can easily move the 4 disks to peg B
also (by using peg C as auxiliary).
 Now we can easily move the largest disk from peg A to
peg C, and finally again apply the solution for 4 disks to
move the 4 disks from peg B to peg C, using the now
empty peg A as an auxiliary.

Prepared by Ramesh singh Saud 55


 To move n disks from peg A to peg C, using peg B
as auxiliary:
1. If n==1, move the single disk from A to C and stop.
2. Move the top n-1 disks from A to B, using C as auxiliary.
3. Move the remaining disk from A to C.
4. Move the n-1 disks from B to C, using A as auxiliary.

Prepared by Ramesh singh Saud 56


 If n=1, step1 results the correct solution.
 If n=2, we know we already have a solution for n-
1=1, so that topmost disk is put at peg B. Now after
performing steps 3 and 4, the solution is completed.
 If n=3, we know we already have a solution for n-
1=2, so that 2 disks are at peg B. Now after
performing steps 3 and 4, the solution is completed.
 Continuing in this manner, we can show that the
solution works for n=1,2,3,4,5,… up to any value
for which we desire a solution.
Prepared by Ramesh singh Saud 57
void transfer(int, char, char, char);
void main()
{ from : the
int n; peg from which
clrscr(); we are
printf("\n Input number of disks in peg A:"); removing disks
scanf("%d", &n);
transfer(n, 'A', 'C', 'B'); to : the peg to
getch(); which we will
}
void transfer(int n, char from, char to, char aux)
take the disks
{ aux: the
if(n==1) auxiliary peg
{
printf("\n Move disk %d from peg %c to peg %c", n, from, to);
return;
}
transfer(n-1,from,aux,to);
printf("\n Move disk %d from peg %c to peg %c", n, from, to);
transfer(n-1,aux,to,from);
}

Prepared by Ramesh singh Saud 58


 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
3  Move disk 1 from peg A to peg C

2 2

1 1 1 1

•Draw the largest disk node with the largest disk number (disk number starts from 1,
with 1 being the smallest disk number) and put it directly to the destination (A->C).
•Draw its two children with the second largest node number i.e. 2.
•Now A->C can be accomplished only through A->B and B->C, so put A->B as left
child and B->C as right child.
•Again draw two children of second largest node i.e. 2 and think how we can generate
A->B and B->C………………………………..Completed
•Finally perform inorder traversal (left-root-right) of the tree to obtain the appropriate
sequence of steps to solve “Tower of Hanoi”.
•Note: On left side, we always have A and on right side, we always have C.
Prepared by Ramesh singh Saud 59
 Write and explain the algorithm for
Tower of Hanoi.

Prepared by Ramesh singh Saud 60


 Consider the function:
void transfer(int n, char from, char to, char temp)
{
if(n>0)
transfer(n-1, from, temp, to);
printf(“\n Move Disk %d from %c to %c”, n, from, to);
transfer(n-1, temp, to, from);
}
Trace the output with the function call:
transfer(3, ‘R’, ‘L’, ‘C’);

Prepared by Ramesh singh Saud 61

You might also like