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

Unit2 Stack

This document provides an overview of stacks as a linear data structure that operates on a Last In First Out (LIFO) principle, detailing its operations such as push and pop, and implementations in C. It also discusses the differences between stacks and arrays, applications of stacks in problem-solving, and the time complexity of stack operations. Additionally, it covers recursion versus iteration, including examples and algorithms for evaluating postfix expressions.

Uploaded by

mrai48851
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)
8 views

Unit2 Stack

This document provides an overview of stacks as a linear data structure that operates on a Last In First Out (LIFO) principle, detailing its operations such as push and pop, and implementations in C. It also discusses the differences between stacks and arrays, applications of stacks in problem-solving, and the time complexity of stack operations. Additionally, it covers recursion versus iteration, including examples and algorithms for evaluating postfix expressions.

Uploaded by

mrai48851
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/ 70

Data Structure

UNIT-2
STACK
KCS-301

Data Structure(KCS-301) Divya Pachauri


1-Abstract Data Type 7-Removal of recursion Problem
solving using iteration and
2- Primitive Stack operations:
recursion with examples such as
Push & Pop,
binary search,
3-Array and Linked
8-Fibonacci numbers, and Hanoi
Implementation of Stack in C,
towers.
4-Application of stack: Prefix and
9-Tradeoffs between iteration and
Postfix Expressions, Evaluation of
recursion.
postfix expression,
5- Iteration and Recursion-
Principles of recursion,
6-Tail recursion,

Data Structure Unit-2 2


STACK
• A stack is a linear data structure, collection of items of the
same type.
• Stack follows the Last In First Out (LIFO) fashion wherein the
last element entered is the first one to be popped out.
• In stacks, the insertion and deletion of elements happen
only at one end point of it. Which is known as top of stack.
• A stack is an Abstract Data Type (ADT), commonly used in
most programming languages. It is named stack as it
behaves like a real-world stack, for example – a deck of
cards or a pile of plates, etc.
Data Structure Unit-2 3
Data Structure Unit-2 4
Operations performed on Stack

1) Push (): This function adds an element to the top of the


Stack.
2) Pop (): This function removes the topmost element from
the stack.
3) IsEmpty(): Checks whether the stack is empty.
4) IsFull (): Checks whether the stack is full.
5) size() returns the size of stack.

Data Structure Unit-2 5


Data Structure Unit-2 6
How Stack Work

1- Initially, we set a pointer Peek/Top to keep the track of the


topmost item in the stack.
2- Initialize the stack to -1. Then, we check whether the stack is
empty through the comparison of Peek to -1 i.e. Top == -1
3- As we add the elements to the stack, the position of the Peek
element keeps updating every time.
4- As soon as we pop or delete an item from the set of inputs,
the top-most element gets deleted and thus the value of
Peek/Top gets reduced.
Data Structure Unit-2 7
Push and Pop Operation in Stack in Data Structure

 The Last-In-First-Out (LIFO) concept is used by Stacks, a type of linear data structure.
 The Queue has two endpoints, but the Stack only has one (front and rear).
 It only has one pointer, top pointer, which points to the stack's topmost element.
 When an element is added to the stack, it is always added to the top, and it can only be removed from the
stack.
 To put it another way, a stack is a container that allows insertion and deletion from the end known as the
stack's top.

LIFO (Last in First Out)


As an actual illustration, consider a stack of dishes stacked on top of one another. We may claim that the plate
we put last comes out first because the plate we put last is on top and we take the plate at the top.

Due to the possibility of understating inventory value, LIFO is not a reliable indicator of ending inventory value.
Due to increasing COGS, LIFO leads to reduced net income (and taxes). However, under LIFO during inflation,
there are fewer inventory write-downs. Results from average cost are in the middle of FIFO and LIFO.

Data Structure Unit-2 8


Implementation of operations in stack
1- If top== -1 -- Stack is empty (under flow
condition)
2- If Top == max-1 --------- Stack is full. [ when we insert an
element we check this condition. ( Overflow condition)

Data Structure Unit-2 9


Stack Vs Array

Stack: A stack is a type of linear data structure whose components may only be added to or removed from the top
side of the list. The Last in First out (LIFO) principle governs stacks, meaning that the element put last is the first
element to be removed. Push operations and pop operations are the terms used to describe the addition and
removal of elements from stacks, respectively.
A pointer named top is used in stack to maintain track of the last piece that is currently present in the list.

Array: A group of objects kept in consecutive memory regions is known as an array.


The goal is to group objects of the same category for storage. As a result, it is simpler to determine each element's
position by simply adding an offset to a base value, or the address in memory where the array's first element is stored
(generally denoted by the name of the array)

Data Structure Unit-2 10


Data Structure Unit-2 11
Data Structure Unit-2 12
Data Structure Unit-2 13
Data Structure Unit-2 14
Data Structure Unit-2 15
Data Structure Unit-2 16
Data Structure Unit-2 17
Data Structure Unit-2 18
Data Structure Unit-2 19
Data Structure Unit-2 20
Algorithm and C function to insert an element
void Push()
{
int x;
if(Top==Size-1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
stack_array[Top]=x;
}
}
Data Structure Unit-2 21
Algorithm and C function to insert an element

Push(stacktop, size,x)
Here we insert an element x into stack, where size is the size of stack and we have
to insert an element using Top.
1- if top= size-1 then write stack is empty or Overflow and go to step 4
2- set Top= Top+1
3- set x into array of stack or Stack(Top)= x
4- exit

Data Structure Unit-2 22


Data Structure Unit-2 23
Data Structure Unit-2 24
Data Structure Unit-2 25
Data Structure Unit-2 26
Data Structure Unit-2 27
Data Structure Unit-2 28
Algorithm and C function to delete an element
Pop( Stack, Top, X) void Pop()
We have to define this…….. {
if(Top==-1)
1- if top= -1 then write stack is empty {
and go to step 4 printf("\nUnderflow!!");
2- set x= stack[top] }
3- set top=top-1 else
4- stop {
printf("\ndeleted element:
%d",stack_array[Top]);
Top=Top-1;
}
}
Data Structure Unit-2 29
#define Size 4
int Top=-1, stack_array[Size]; void Push()
void Push(); { int x;
void Pop(); if(Top==Size-1)
{ printf("\nOverflow!!");
void show();
}
int main() else
{ { printf("\nEnter element to be inserted to the stack:");
int choice; scanf("%d",&x);
while(1) Top=Top+1;
stack_array[Top]=x;
{
}
printf("\nOperations performed by Stack"); }
printf("\n1.Push the element\n2.Pop the void Pop()
element\n3.Show\n4.End"); { if(Top==-1)
printf("\n\nEnter the choice:"); { printf("\nUnderflow!!");
scanf("%d",&choice); }
switch(choice) else
{ printf("\nPopped element: %d",stack_array[Top]);
{
Top=Top-1;
case 1: Push(); break; }
case 2: Pop(); break; }
case 3: show(); reak;
case 4: exit(0);
default: printf("\nInvalid choice!!");
} Data Structure Unit-2 30
} }
void show() Output-
{ Operations performed by Stack
if(Top==-1) 1.Push the element
{ 2.Pop the element
printf("\nUnderflow!!"); 3.Show
} 4.End
else
{ Enter the choice:2
printf("\nElements present in the stack: Popped element: 10
\n");
for(int i=Top;i>=0;--i) Operations performed by Stack
printf("%d\n",stack_array[i]); 1.Push the element
} 2.Pop the element
} 3.Show
4.End

Enter the choice:3


Underflow!!
Data Structure Unit-2 31
Time Complexity of Stack Operations

 only a single element can be accessed at a time in Stacks.

While performing push() and pop() operations on the stack,


it takes-------------------------- O(1) time.

Data Structure Unit-2 32


Data Structure Unit-2 33
Data Structure Unit-2 34
Data Structure Unit-2 35
Data Structure Unit-2 36
Data Structure Unit-2 37
Data Structure Unit-2 38
Data Structure Unit-2 39
Data Structure Unit-2 40
Data Structure Unit-2 41
Data Structure Unit-2 42
Data Structure Unit-2 43
Data Structure Unit-2 44
Data Structure Unit-2 45
Applications of Stack
 The Stack is used to solve a few of the general problems like:
1- Reversing a string
2- Tower of Hanoi
3- N queens problem
4- Parenthesis balancing in compiler
5- Infix to prefix conversion, Infix to postfix conversion etc.

Data Structure Unit-2 46


Applications
The way to write arithmetic expression is known as a notation. An
arithmetic expression can be written in three different but equivalent
notations, i.e., without changing the essence or output of an
expression. These notations are −
1- Infix Notation 2- Prefix (Polish) Notation 3- Postfix (Reverse-
Polish) Notation
Sr.No. Infix Notation Prefix Notation Postfix Notation
1 a+b +ab ab+
2 (a + b) ∗ c ∗+abc ab+c∗
3 a ∗ (b + c) ∗a+bc abc+∗
4 a/b+c/d +/ab/cd ab/cd/+
5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗
Data Structure Unit-2 47
Expressions: Convert in to postfix

1- A + (B* C – ( D/E^F)*G)*H
2- ((A+B)*D)^(E-F)
3- A+((B+C) + (D+E)*F)/G
4- A-B/(C*D^F)
5- (A-B/C) * (D*E-F)
6- A/B^C-D

Data Structure Unit-2 48


SNO SYMBOL STACK EXPRESSION
(A+(B*C)/D) 1 ( ( ----------
2 A ( A
3 + (+ A
4 ( (+( A
5 B (+( AB
6 * (+(* AB
7 C (+(* ABC
8 ) (+ ABC*
9 / (+/ ABC*
10 D (+/ ABC*D
11 ) ------- ABC*D/+

Data Structure Unit-2 49


SNO SYMBOL STACK EXPRESSION
1 ( ( ---------------------
2 A ( A
(A + (B* C – ( D/E^F)*G)*H) 3 + (+ A
4 ( (+( A
5 B (+( AB
6 * (+(* AB
7 C (+(* ABC
8 - (+(- ABC*
9 ( (+(-( ABC*
10 D (+(-( ABC*D
11 / (+(-(/ ABC*D
12 E (+(-(/ ABC*DE
13 ^ (+(-(/^ ABC*DE
14 F (+(-(/^ ABC*DEF
15 ) (+(- ABC*DEF^/
16 * (+(-* ABC*DEF^/
17 G (+(-* ABC*DEF^/G
18 ) (+ ABC*DEF^/G*-
19 * (+* ABC*DEF^/G*-
20 H (+* ABC*DEF^/G*-H
21 ) Data-------
Structure Unit-2 ABC*DEF^/G*-H*+ 50
Algorithm of Evaluation of a post fix expression
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 “)” is uncounted.
3- if an operands is occur,, put is into Stack.
4- if an operator occur then
4.1 remove the top two element from P (A and B)
4.2 Evaluate B*A
4.3 Place the result of 4.2 into stack
5- set value equal to the top element on stack
6- exit
Data Structure Unit-2 51
Solve the following postfix expression
P: 5 6 2 + * 12 4 / -
SYMBOL STACK
5 5
6 56
2 562
+ 58
* 40
12 40 12
4 40 12 4
/ 40 3
- 37

Data Structure Unit-2 52


Solve the following postfix expression
P: 12 7 3 - / 2 1 5 + * +
SYMBOL STACK
12 12
7 12 7
3 12 7 3
- 12 4
/ 3
2 3 2
1 3 2 1
5 3 2 1 5
+ 3 2 6
* 3 12
+ 15
Data Structure Unit-2 53
Difference between Recursion and Iteration
SNO On the Recursion Iteration
basis of
1 Basic Recursion is the process of calling a In iteration, there is a repeated execution of the set of
function itself within its own code. instructions. In Iteration, loops are used to execute the
set of instructions repetitively until the condition is false.
2 Syntax There is a termination condition is The format of iteration includes initialization, condition,
specified. and increment/decrement of a variable.
3 Termination The termination condition is defined Here, the termination condition is defined in the
within the recursive function. definition of the loop.
4 Applied It is always applied to functions. It is applied to loops.
5 Speed It is slower than iteration. It is faster than recursion.
6 Memory It uses more memory as It uses less memory.
compared to iteration.
7 Code size The code size in recursion is The code size in iteration is larger than the code
smaller than the code size in size in recursion.
iteration.
Data Structure Unit-2 54
Recursion Iteration
// method to find factorial of given number // Method to find the factorial of a given
int factorialUsingRecursion(int n) number
{ int factorialUsingIteration(int n)
if (n == 0) {
return 1; int res = 1, i;

// recursion call // using iteration


return n * factorialUsingRecursion(n - 1); for (i = 2; i <= n; i++)
} res *= i;

return res;
}

Data Structure Unit-2 55


int main()
{
int num = 5;
printf(“%d Factorial of a number using Recursion is: " ,
factorialUsingRecursion(5);

printf(“%d Factorial of a number using Recursion is: " ,


factorialUsingIteration(5);

return 0;
}

Data Structure Unit-2 56


Types of recursion
1- Direct Recursion--- When a function calls itself within the
same function repeatedly, it is called the direct recursion.
2- Indirect Recursion
3- Tail Recursion
4- No Tail/ Head Recursion
5- Linear recursion
6- Tree Recursion

Data Structure Unit-2 57


Types of recursion
1- Direct Recursion--- When a function calls itself within the
same function repeatedly, it is called the direct recursion.

2- Indirect Recursion
3- Tail Recursion
4- No Tail/ Head Recursion
5- Linear recursion
6- Tree Recursion

Data Structure Unit-2 58


Types of recursion
1- Direct Recursion--- When a function calls itself within the same function repeatedly, it is
called the direct recursion.
fun ( )
{
fun( );
}
Ex Fibonacci series
2- Indirect Recursion- When a function is mutually called by another function in a circular
manner, the function is called an indirect recursion function.
fun1 ( )
{
fun2( );
}
fun2 ( )
{
fun1( );
}
Data Structure Unit-2 59
3- Tail Recursion-- A recursive function is called the tail-recursive if the function makes recursive calling
itself, and that recursive call is the last statement executes by the function. After that, there is no
function or statement is left to call the recursive function.
#include <stdio.h>
// function definition
void fun1(int num)
{

if (num == 0)
return ;
else
printf ("\n Number is: %d", num); // print the number
return fun1 (num - 1); // recursive call at the end in the fun() function
}
int main ()
{
fun1(10); // pass 10 as integer argument
return 0;
}

Data Structure Unit-2 60


Fibonacci Series
#include<stdio.h> int main ()
int fibo_num (int i) {
{ int i;
// if the num i is equal to 0, return 0; // use for loop to get the first 10 fibonacci series
if ( i == 0) for ( i = 0; i < 10; i++)
{ {
return 0; printf (" %d \t ", fibo_num (i));
} }
if ( i == 1) return 0;
{ }
return 1;
}
return fibo_num (i - 1) + fibo_num (i -2);
}

Data Structure Unit-2 61


Tower Of Hanoi
• The tower of Hanoi is a mathematical puzzle. It consists of three
rods and a number of disks of different sizes which can slide to
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. We
have to obtain the same stack on the third rod.
• The objective of the puzzle is to move the entire stack to
another rod, obeying the following simple rules−
• Only one disk can be moved at a time.
• Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack i.e. a disk can only
be moved if it is the uppermost disk on a stack.
Data Structure Unit-2 62
Data Structure Unit-2 63
#include<stdio.h>
void TOH(int n,char x,char y,char z)
{
if(n>0) {
TOH(n-1,x,z,y);
printf("\n%c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n;
printf("enter the value of n");
scanf("%d",&n);
TOH(n,'A','B','C');
}

Data Structure Unit-2 64


Linear Search
• Linear Search is defined as a sequential search algorithm
that starts at one end and goes through each element of a
list until the desired element is found, otherwise the search
continues till the end of the data set. It is the easiest
searching algorithm

Data Structure Unit-2 65


Binary Search
• The basic steps to perform Binary Search are:
• Begin with the mid element of the whole array as a search key.
• If the value of the search key is equal to the item then return an
index of the search key.
• Or if the value of the search key is less than the item in the
middle of the interval, narrow the interval to the lower half.
• Otherwise, narrow it to the upper half.
• Repeatedly check from the second point until the value is found
or the interval is empty.

Data Structure Unit-2 66


Data Structure Unit-2 67
• Binary Search Algorithm can be implemented in the following two ways
1- Iterative Method 2- Recursive Method

binarySearch(arr, x, low, high)


repeat till low = high
• mid = (low + high)/2
• if (x == arr[mid])
• return mid

• else if (x > arr[mid]) // x is on the right side
• low = mid + 1

• else // x is on the left side
• high = mid - 1
Data Structure Unit-2 68
2- Recursive Method
binarySearch(arr, x, low, high)
if low > high
return False

else
mid = (low + high) / 2
if x == arr[mid]
return mid

else if x > arr[mid] // x is on the right side


return binarySearch(arr, x, mid + 1, high)

else // x is on the right side


return binarySearch(arr, x, low, mid - 1)
Data Structure Unit-2 69
Tradeoffs between iteration and recursion
The following table highlights all the important differences between recursion and iteration −

Recursion Iteration

Recursion uses the selection structure. Iteration uses the repetition structure.

Infinite recursion occurs if the step in recursion doesn't reduce the problem to
An infinite loop occurs when the condition in the loop
a smaller problem. It also becomes infinite recursion if it doesn't convert on a
doesn't become False ever.
specific condition. This specific condition is known as the base case.

Iteration uses the CPU cycles again and again when an


The system crashes when infinite recursion is encountered.
infinite loop occurs.

Recursion terminates when the base case is met. Iteration terminates when the condition in the loop fails.

Recursion is slower than iteration since it has the overhead of maintaining and Iteration is quick in comparison to recursion. It doesn't
updating the stack. utilize the stack.

Recursion uses more memory in comparison to iteration. Iteration uses less memory in comparison to recursion.

Recursion reduces the size of the code. Iteration increases the size of the code.
Data Structure Unit-2 70

You might also like