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

Lec 20 Stack

The document provides an overview of stacks as a data structure that follows the Last In First Out (LIFO) principle, detailing operations such as push, pop, peek, isFull, and isEmpty. It explains stack implementation using arrays and linked lists, including examples of push and pop operations, and discusses applications of stacks in programming, such as function calls and expression evaluations. Additionally, it covers infix, prefix, and postfix notations, along with the conversion process from infix to postfix expressions.

Uploaded by

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

Lec 20 Stack

The document provides an overview of stacks as a data structure that follows the Last In First Out (LIFO) principle, detailing operations such as push, pop, peek, isFull, and isEmpty. It explains stack implementation using arrays and linked lists, including examples of push and pop operations, and discusses applications of stacks in programming, such as function calls and expression evaluations. Additionally, it covers infix, prefix, and postfix notations, along with the conversion process from infix to postfix expressions.

Uploaded by

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

STACKS

01/21/2025
Thapar Institute of Engineering & Technology
Introduction
 A stack is a data structure that provides storage of data in such a way that the
element stored last will be retrieved first.

 This method is also called LIFO – Last In First Out.

Example:

 In real life we can think of stack as a stack of copies, stack of plates etc.

 The first copy put in the stack is the last one to be removed.

 Similarly last copy to put in the stack is the first one to be removed.

Thapar Institute of Engineering & Technology


Thapar Institute of Engineering & Technology
Operations on Stack
 A stack is a linear data structure.
 It is controlled by two operations: push and pop.
 Both the operations take place from one end of the stack, usually
called top.
 Top points to the current top position of the stack.
 Push operation adds an element to the top of the stack.
 Pop operation removes an element from the top of the stack.
 These two operations implements the LIFO method.

Thapar Institute of Engineering & Technology


Operations

1. Push()
• It is the term used to insert an element into a stack.
2. Pop()
• It is the term used to delete an element from a stack.
3. peek()
• Get the top data element of the stack, without removing it.
4. isFull()
• Check if stack is full.
5. isEmpty()
• Check if stack is empty.

Thapar Institute of Engineering & Technology


Thapar Institute of Engineering & Technology
Implementation of Stack
Stack can be implemented in two ways:

 As an Array
 As a Linked List

Thapar Institute of Engineering & Technology


Stack as an Array
Array implementation of stack uses:
4

 an array to store data 3


 an integer type variable usually called the top,
30
which points to the top of the stack. 2

2 20 1

TO 10 0
NOTE: The variable top contains the index number P

of the top most filled element of the array.

Thapar Institute of Engineering & Technology


Push Operation
 Initially when the stack is empty, TOP can have any integer value other
than any valid index number of the array. Let TOP = -1;
 The first element in the empty stack goes to the 0th position of the array
and the Top is initialized to value 0.
 After this every push operation increase the TOP by 1 and inserts
new data at that particular position.
 As arrays are fixed in length, elements can not be inserted beyond the
maximum size of the array.
 Pushing data beyond the maximum size of the stack results in “data
overflow”.

Thapar Institute of Engineering & Technology


Push Operation Explained

NOTE: Pushing one more element into the stack will result in
overflow. Thapar Institute of Engineering & Technology
void push()
{
A B C D E
if(top>=n-1)
0 1 2 3 TOP = 4 5 6 7 8 9
{
printf("\n STACK is over flow"); A B C D E F

0 1 2 3 4 TOP =5 6 7 8 9

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
Thapar Institute of Engineering & Technology
Pop Operation
 The pop operation deletes the most recently entered item from
the stack.
 Any attempt to delete an element from the empty stack results
in “data underflow” condition.
 The variable TOP contains the index number of the current top
position of the stack.
 Each time the pop operation is performed, the TOP variable is
decremented by 1.

Thapar Institute of Engineering & Technology


POP OPERATION EXPLAINED

top = 2

Thapar Institute of Engineering & Technology


void pop()
{
if(top = = -1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n The popped elements is %d", stack[top]);
top--;
}
}
Thapar Institute of Engineering & Technology
PEEK OPERATION
 Peek operation involves returning the element which is
present at the top of the stack without deleting it.
 Underflow condition can occur if we try to return the top
element in an already empty stack.

Thapar Institute of Engineering & Technology


int peek()
{
if (top == -1)
{
printf("Underflow");
return 0;
}
else
{
return stack [top];
}
}
Thapar Institute of Engineering & Technology
DISPLAY OPERATION
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

} Thapar Institute of Engineering & Technology


STACK AS A LINKED LIST
Linked list implementation of stack uses
 A linked list to store data
 A pointer TOP pointing to the top most position of the stack.

NOTE: Each node of a stack as a linked list has two parts : data part and link
part and is created with the help of self referential structure.
The data part stores the data and link part stores the address of the next node of
the linked list.
NODE

TOP

DAT NEX
A Thapar Institute of Engineering & Technology
Push operation using Linked List

Push 5 Push 10

Push 20

Thapar Institute of Engineering & Technology


Pop Operation using Linked List

Pop Pop

Thapar Institute of Engineering & Technology


PROGRAM TO ILLUSTRATE
OPERATIONS ON STACK
AS A LINKED LIST : Explanation

struct node
Self Referential Structure: These are special structures
{
which contains pointers to themselves.
int data;
Here, next is a pointer of type node itself.
struct node *next;
Self Referential structures are needed to create Linked
};
Lists.

Thapar Institute of Engineering & Technology


PROGRAM TO ILLUSTRATE OPERATIONS
ON STACK
void stack::push()AS A LINKED LIST : Explanation
{
node *temp; // pointer of type node
temp= (struct node*)malloc(sizeof(struct node)); // new operator will create a new node and address of
// new node is stored in temp

printf(“Enter data”); These lines will store data to newly


scanf(“%d”,temp->data); created node.

temp- // address stored in TOP gets stored in next of newly created node.
>next=top;

top=temp; // Top will contain address of newly created node

Thapar Institute of Engineering & Technology


PROGRAM TO ILLUSTRATE OPERATIONS
ON STACK
void stack::pop()AS A LINKED LIST : Explanation
{
if(top!=NULL) // if stack is not empty
{
struct node *temp=top; // temp is a pointer containing address of first node
top=top->next; // top will now contain address of second node

printf(“%d”, temp=data); // This line will display data stored in deleted node

free (temp) ; // delete operator will delete the node stored at temp
}
else
printf(“underflow”);
}

Thapar Institute of Engineering & Technology


APPLICATIONS OF
ASTACK
stack is an appropriate data structure on which information is stored and then
later retrieved in reverse order. The application of stack are as follows:

 When a program executes, stack is used to store the return address at time of
function call. After the execution of the function is over, return address is popped
from stack and control is returned back to the calling function.

 Converting an infix expression o postfix operation and to evaluate the


postfix expression.

 Reversing an array, converting decimal number into binary number etc.

 In computations like decimal to binary conversion

 In Backtracking algorithms
Thapar Institute of Engineering & Technology
Reverse of String or List
●We can accomplish this task by pushing each character or
member from the string/list in the order it appears
●When the line is finished, characters are then popped off the
stack

“They come off in a reverse order”

Thapar Institute of Engineering & Technology


Reverse string – Name=“Angel”
L
P E E
G G G
U
N N N N
S A A A A A

E
P
G G
O N N N
A
P
A A A
Name : Name : Name : Name : Name :
“L” “LE” “LEG” “LEGN” “LEGNA” Thapar Institute of Engineering & Technology
Arithmetic Expressions

Arithmetic expressions have:

operands (variables or numeric constants).

Operators
Binary : +, -, *, / ,%
Unary: -

Priority convention:
*, /, % have medium priority
+, - have lowest priority

Thapar Institute of Engineering & Technology


Infix, Prefix, Postfix

• Example: arithmetic expression a + b consists of operands a, b and operator +.

• Infix notation
• Is format where operator is specified in between the two operands.
• a+b

• Prefix notation
• Is format where operator is specified before the two operands.
• +ab

• Postfix notation
• Is format where operator is specified after the two operands. Postfix notation is also called RPN
or Reverse Polish Notation.
• ab+

Thapar Institute of Engineering & Technology


Infix Postfix
Prefix Notation
Notation Notation
A+B*C +A * B C A BC*+

(A+B) * C *+ABC AB+C*

A–B+C +–ABC AB–C+

A – (B+C) –A+BC A BC+–

Thapar Institute of Engineering & Technology


Infix Notation Prefix Notation Postfix Notation

A+B + AB AB +

(A - C) + B + - ACB AC – B +

A+(B*C) + A * BC ABC *+

(A+B)/(C-D) /+ AB – CD AB + CD -/

(A + (B * C))/(C – (D * B)) /+ A * BC – C * DB ABC * + CDB * - /

Thapar Institute of Engineering & Technology


Why use Prefix and Postfix?
• To avoid ambiguous
• Infix notation requires precedence and associativity rules to
disambiguate it, or addition of extra parentheses that are not
usually considered part of the notation.
• Therefore, as long as the number of arguments to each
operator are known in advance, both prefix and postfix
notation are entirely unambiguous

• Example :
• "* + 5 6 3" is (5+6)*3, and cannot be interpreted as 5+(6*3),
whereas parenthesis is required to achieve with infix.

Thapar Institute of Engineering & Technology


NEED OF POSTFIX
EXPRESSION
The postfix expressions are special because

 They do not use parenthesis


 The order of expression is uniquely reconstructed from
the expression itself.

These expressions are useful in computer applications.

Thapar Institute of Engineering & Technology


Infix to Postfix Conversion
• Example: Infix notation A + B – C

Þ (A B + ) - C
ÞAB+C–

• Example: Infix notation A + B * C

Þ A + (B C *)
Þ A B CInfix
Example: * + notation a + c – r / b * r

Þ a + c – (r b /) * r
Þ a + c – (r b / r *)
Þ (a c +) – (r b / r * )
Þ ac+rb/r*-

Thapar Institute of Engineering & Technology


CONVERTING INFIX TO POSTFIX
EXPRESSION
CONVERT_I_P(I,P,STACK) Where I = infix expression, P = postfix expression, STACK = stack as an
array
Step 1. Push ‘(‘ into STACK and add ‘)’ to the end of I.
Step 2. Scan expression I from left to right and repeat steps 3-6 for each element of I until the stack is
empty. STEPS INFIX OPERATOR
STACK
POSTFIX

Step 3. If scanned element =‘(‘ , push it into the STACK. 1

2
Step 4. If scanned element = operand, add it to P.
Step 5. If scanned element = operator, then:
a) Repeatedly pop from STACK and add to P each operator from the top of the stack until the
operator at the top of the stack has lower precedence than the operator extracted from I.
b) Add scanned operator to the top of the STACK.
Step 6. If scanned element = ‘)’ then:
b) Repeatedly pop from STACK and add to P each operator until the left parenthesis is
encountered.
Thapar Institute of Engineering & Technology
Example 1: Infix notation A - B

STEPS INFIX OPERATOR POSTFIX


STACK
1 A ( A
2 - (- A
3 B (- AB
4 ) AB-

Thapar Institute of Engineering & Technology


Example: Infix to Postfix
• Example 2: Infix notation A + B - C

STEPS INFIX OPERATOR POSTFIX


STACK
1 A ( A
2 + (+ A
3 B (+ AB
4 - (- AB+
5 C (- AB+C
6 ) empty AB+ C -

Thapar Institute of Engineering & Technology


Example of Infix to Postfix
• Example 3: Infix notation A + B * C

STEPS INFIX OPERATOR POSTFIX


STACK
1 A ( A
2 + (+ A
3 B (+ AB
4 * (+ * AB
5 C (+ * ABC
6 ) ABC *
ABC *+

Thapar Institute of Engineering & Technology


x – (y * a / b – (z + d * e) + c) / f
Infix operatorStack Postfix
x ( x
- (- x
( (-( x
y (-( xy
* (-( * xy
a (-( * xya
/ (-( / xya *
b (-( / xya * b
- (-( - xya * b/
( (-( -( xya * b/
z (-( -( xya * b/z

Thapar Institute of Engineering & Technology


x – (y * a / b – (z + d * e) + c) / f
INFIX OPERATORSTACK POSTFIX
+ (-( -( + xya * b/z
d (-( - ( + xya * b/zd
* (-( - ( + * xya * b/zd
e (-( - ( + * xya * b/zde
) (-( - xya * b/zde *+
+ (-( + xya * b/zde *+-
c (-( + xya * b/zde *+ -c
) (- xya * b/zde *+ -c +
/ (- / xya * b/zde *+ -c +
f (- / xya * b/zde *+ -c + f
) xya * b/zde *+- c + f /-

Thapar Institute of Engineering & Technology


EVALUATION OF POSTFIX
EXPRESSION
Evaluate(P, result, STACK)
where P=Postfix expression, STACK =stack, result=to hold the result of evaluation

Step 1. Scan the postfix expression P from left to right and repeat the steps 2,
3 until the STACK is empty.
Step 2. If the scanned element = operand, push it into the STACK.
Step 3. If the scanned element = operator, then
a) Pop the two operands viz operand A and operand B from the
STACK.
b) Evaluate ((operand B) operator (operand A))
c) Push the result of evaluation into the STACK.
Thapar Institute of Engineering & Technology
Thapar Institute of Engineering & Technology
Thapar Institute of Engineering & Technology
Thapar Institute of Engineering & Technology
Recursion

• The process in which a function calls itself directly or indirectly


is called recursion and the corresponding function is called as
recursive function.
• Using recursive algorithm, certain problems can be solved quite
easily.

Thapar Institute of Engineering & Technology


• We have a bigger problem whose solution is difficult to find
• We divide/decompose the problem into smaller (sub) problems
•Keep on decomposing until we reach to the smallest sub-problem
(base case) for which a solution is known or easy to find
•Then go back in reverse order and build upon the solutions of the sub-
problems
• Recursion is applied when the solution of a problem depends
on the solutions to smaller instances of the same problem

Thapar Institute of Engineering & Technology


Recursive Function
A function which calls itself
int factorial ( int n ) {
if ( n == 0) // base case
return 1;
else // general/ recursive
case
return n * factorial ( n - 1 );
}

Thapar Institute of Engineering & Technology


Finding a recursive solution

• Each successive recursive call should bring you closer to a situation


in which the answer is known (cf. n-1 in the previous slide)
• A case for which the answer is known (and can be expressed
without recursion) is called a base case
• Each recursive algorithm must have at least one base case, as well
as the general recursive case

Thapar Institute of Engineering & Technology


Recursion vs. Iteration: Computing N!

• The factorial of a positive integer n, denoted n!, is defined as the


product of the integers from 1 to n. For example, 4! = 4·3·2·1 = 24.
Iterative Solution

Recursive Solution

Thapar Institute of Engineering & Technology


Recursion in Action: factorial(n)

Base case
factorial (5) = 5 x factorial (4)
arrived Some
= 5 x (4 x factorial (3)) concept from
elementary
= 5 x (4 x (3 x factorial (2)))
maths: Solve the
= 5 x (4 x (3 x (2 x factorial (1)))) inner-most
bracket, first, and
= 5 x (4 x (3 x (2 x (1 x factorial (0)))))
then go outward
= 5 x (4 x (3 x (2 x (1 x 1))))
= 5 x (4 x (3 x (2 x 1)))
= 5 x (4 x (3 x 2))
= 5 x (4 x 6)
= 5 x 24
= 120

Thapar Institute of Engineering & Technology


Type of Recursion

• Direct Recursion: When in the body of a method there is a call


to the same method, we say that the method is directly
recursive.

Thapar Institute of Engineering & Technology


• Indirect Recursion: A function fun is called indirect recursive if it
calls another function say fun_new and fun_new calls fun
directly or indirectly.

Thapar Institute of Engineering & Technology


Tail Recursion

• In the given recursive program, only one recursive function call


is there and that is also at the end of the program.
• In this no operation are pending to be performed when the
recursive function returned to its caller.

Thapar Institute of Engineering & Technology


Non-tail Recursion

• In a given-recursive program, after recursive call there is


something to do, then it is called non-tail recursion program.

Thapar Institute of Engineering & Technology


Nested Recursion

• A more complicated case of recursion is found in definitions in


which a function is not only defined in terms of itself but it is
also used as one of the parameters.

The Ackermann function

 m 1 if n  0,

A(n, m)  A(n 1,1) if n  0, m 


0, A(n 1, A(n, m 1)) otherwise

Thapar Institute of Engineering & Technology


How to write a recursive function?

• Determine the size factor (e.g. n in factorial(n))


• Determine the base case(s)
• the one for which you know the answer (e.g. 0! = 1)
• Determine the general case(s)
• the one where the problem is expressed as a smaller version of
itself (must converge to base case)

Thapar Institute of Engineering & Technology


Why Stack Overflow error occurs in
recursion?
• If the base case is not reached or not defined, then the stack
overflow problem may arise. Let us take an example to
understand this.

If fact(10) is called, it will call fact(9),


fact(8), fact(7) and so on but the
number will never reach 100. So, the
base case is not reached. If the
memory is exhausted by these
functions on the stack, it will cause a
stack overflow error.

Thapar Institute of Engineering & Technology


Implementation

• Recursion is implemented by means of stacks.


• Generally, whenever a function (caller) calls
another function (callee) or itself as callee, caller
function transfers execution control to the callee.
• This transfer process may also involve some data to be passed from the caller to
the callee.
• This implies, the caller function has to suspend its execution temporarily and
resume later when the execution control returns from the callee function.
• Here, the caller function needs to start exactly from the point of execution where it
puts itself on hold. It also needs the exact same data values it was working on.
• For this purpose, an activation record (or stack frame) is created for the caller
Thapar Institute of Engineering & Technology
Thapar Institute of Engineering & Technology
Recursive program to linearly search an
element in a given array
• The idea is to
compare x with first
element in arr[]. If
element is found at
first position, return
it. Else recur for
remaining array and
x.

Thapar Institute of Engineering & Technology


Efficiency of recursion
• Recursion is not efficient because:
• It may involve much more operations than necessary (Time complexity)
• It uses the run-time stack, which involves pushing and popping a lot of data in and out of the stack, some of it
may be unnecessary (Time and Space complexity)
• Both the time and space complexities of recursive functions may be considerably higher than their
iterative alternatives
• The recursive program has greater space requirements than iterative program as all functions will
remain in the stack until the base case is reached. It also has greater time requirements because
of function calls and returns overhead.
• Recursion provides a clean and simple way to write code. Some problems are inherently recursive
like tree traversals, Tower of Hanoi, etc. For such problems, it is preferred to write recursive code.
• Use recursion when:
• The depth of recursive calls is relatively “shallow” compared to the size of the problem. (factorial is deep)
• The recursive version does about the same amount of work as the non-recursive version. (fibonacci does more
work)
• The recursive version is shorter and simpler than the non-recursive solution (towers of hanoi)
Thapar Institute of Engineering & Technology
Fibonacci Series

• In case of fibonacci series, next number is the sum of


previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13,
21 etc.
• The first two numbers of fibonacci series are 0 and 1.

Thapar Institute of Engineering & Technology


#include <stdio.h>
int fibonacci(int num){ // fibonacci() funtion definition
if (num == 0) { // first base condition check
return 0; } // retuning 0, if condition meets
else if (num == 1){ // second base condition check
return 1; } // returning 1, if condition meets
else{ // else calling the fibonacci() function recursively till we get to the base conditions
return fibonacci(num - 1) + fibonacci(num - 2); }} // recursively calling the fibonacc() function and then
adding them
int main() {
int num, i; // variable to store how many elements to be displayed in the series
printf("Enter the number of elements to be in the series : ");
scanf("%d", &num); // taking user input
for (i = 0; i < num; i++) {
printf("%d, ", fibonacci(i)); } // calling fibonacci() function for each iteration and printing the
returned value
return 0; }

Thapar Institute of Engineering & Technology


Tower of Hanoi
It consists of three rods or towers, and a number of disks of different sizes
which can slide onto any rod.

The puzzle starts with the disks in a neat stack in ascending order of size on
one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod,
obeying the following rules:
• Only one disk must be moved at a time.

• Each move consists of taking the upper disk from one of the rods and
sliding it onto another rod, on top of the other disks that may
already be present on that rod.

• No disk may be placed on top of a smaller disk.

Thapar Institute of Engineering & Technology


Thapar Institute of Engineering & Technology
Algorithm

•TOWER(N, BEG, AUX, END)


1. If N = 1 then
a. Write BEG --> END
b. Return
2. [Move N-1 disks from peg BEG to peg AUX]
• Call TOWER(N-1, BEG, END, AUX)
3. Write BEG --> END
4. [Move N-1 disks from peg AUX to peg END]
• Call TOWER(N-1, AUX, BEG, END)
5. Return.

Thapar Institute of Engineering & Technology


For N=3 , how will this recursion solve
the problem as shown Tower(1,A,B, A C
C) ( 1)

Tower(2,A,C, A A B
B) B (2)
C B (3)
Tower(1,C,A,
Tower(3,A,B,C) A B) A. C
C Tower(1,B,C, (4)
A)
B. A (5)
Tower(2,B,A, B C B C
C) (6)
Tower(1,A,B, A C
C) (7)

Thapar Institute of Engineering & Technology


 The puzzle can be played with any number of disks.

 The minimum number of moves required to solve a Tower of Hanoi puzzle is

2n - 1
where n is the number of disks.
 Explicit Pattern
 Number of Number of
Disks Moves
1 1
2 3
3 7
 Powers of two help reveal the 4 15
5 31
pattern:
 Number of Disks (n) Number of
Moves
1 2^1 - 1 = 2 - 1
=1
2 2^2 - 1 = 4 - 1
=3
3 2^3 - 1 = 8 - 1
=7 Thapar Institute of Engineering & Technology
For N=4 , how will this recursion solve the
problem as shown

Thapar Institute of Engineering & Technology

You might also like