Stack

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

MODULE -IV

DATA STRUCTURES USING C


22CSE13
MODULE-III:SYLLABUS

Stack Data Structure: Definition, Representation and Working


of Stack in Data Structures, Basic operations on stack: Push (),
Pop (), Peek (), isfull (), isempty (), Implementation of stack Using
Arrays
Applications of Stack: Recursion, Fibonacci series.
STACK
• A stack is a linear data structure, where elements are stacked on top of each
other.
• It is a Last In First Out (LIFO) structure. -Only the last element added can be
accessed. Every time an element is added or deleted , it goes on the top of the
stack just like a pile of objects.

Real life example


• A pile (or stack!) of plates in a canteen; plates are stacked on top of each other.
Department of ISE
A customer takes a plate from the top. If for some reason they wanted to
access the second plate, they would have to remove the top one first.
Last In First Out (LIFO)

C top
B top B B top
A A A A top
A top
Stack Operations
• In stack data structure mainly performs two operations

• Push(): Insertion of any item in stack is called push.


• Pop(): deletion of any item from stack is called pop.
• peek() − get the top data element of the stack, without removing it.
• isFull() − check if stack is full or overflow.
• isEmpty() − check if stack is empty or underflow.

• Both Push(),Pop() operations takes place from one end-top


CONDITIONS
• Overflow: If we try to insert a new element in the stack top(push)
which is already full, then the situation is called stack overflow

• Stack is full when(top==maxsize-1)


• Underflow: If we try to delete an element(pop) from an empty stack,
the situation is called stack underflow

• Stack is empty when (top==-1)


❖ Algorithm for PUSH operation
• Check if the stack is full or not.
• If the stack is full, then print error of overflow and exit
the program.
• If the stack is not full, then increment the top and
add the element.
❖ Algorithm for POP operation
• Check if the stack is empty or not.
Department of ISE

• If the stack is empty, then print error of underflow and exit the
program.
• If the stack is not empty, then print the element at the top and
decrement the top.
Insertion of any item –push().

• Top is incremented by 1
Function for push() operation:

void push() //Inserting element into the stack


{
int item,n;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
elseDepartment of ISE

{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
Deletion of any item-pop()

• Top is decremented by 1
Function for pop() operation

void pop() //deleting an element from the stack


{
int item;

if(top==-1)
printf("Stack Underflow:");

else
{
item=stack[top];
} top=top-1;
Department of ISE
printf("\nThe poped element: %d\t",item);

}
function to check if the stack is full

void isfull(int top)


{
if(top = = maxsize -1)
{

printf(“Stack is full\n”);
}
else
{
printf(“Stack is not full\n”);

}
}
function to check if the stack is empty

void isempty(int top)


{
if(top = = -1)
{

printf(“Stack is empty\n”);
}
else
{
printf(“Stack is not empty\n”);

}
}
function for peek()

int peek()
{
if (top == -1)
{
printf("Underflow");
return 0;
}
else
{ In the above code, firstly we are checking whether the stack is empty
return stack [top]; or not. If the stack is empty, the program will print underflow and will
return zero. Otherwise, it will return the top element of the stack
}}
Function for display the elements in stack
void display()
{
int i;
if(top==-1)
{
printf("\nStack is empty!!");
}
else
{
printf("Stack is...");
for(i=top;i>=0;i--)
printf("%d\n",stack[i]);
}
}
IMPLEMENTATION OF STACK USING ARRAYS //lab pgm :8

switch(choice)
#include<stdlib.h> {
#include<stdio.h> case 1:
#include<string.h> push();
#define max_size 5 break;
int stack[max_size],top = -1; case 2:
void push(); pop();
void pop(); break;
void display(); case 3:
void peek(); peek();
break;
int main() case 4:
{ display();
int choice; break;
while(choice) case 5:
{ exit(0);
printf("\n\n--------STACK OPERATIONS-----------\n"); break;
printf("1.Push\n"); default:
printf("2.Pop\n"); printf("\nInvalid choice:\n");
printf("3.Peek\n"); break;
printf("4.Display\n"); }
printf("5.Exit\n"); }
printf("\nEnter your choice:\t"); return 0;
scanf("%d",&choice); }
void push() //Inserting element into the stack
{
int item,n; void pop() //deleting an element from the stack
if(top==(max_size-1)) {
{ int item;
printf("\nStack Overflow:"); if(top==-1)
} {
else printf("Stack Underflow:");
{ }
printf("Enter the element to be inserted:\t"); else
scanf("%d",&item); {
top=top+1; item=stack[top];
stack[top]=item; top=top-1;
} printf("\nThe poped element: %d\t",item);
}
}
}
int peek()
{
int item; void display()
if(top==-1) {
{ int i;
printf("Stack Underflow:"); if(top==-1)
} {
else printf("\nStack is Empty:");
{ }
return stack[top]; else
{
} printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
} {
printf("%d\n",stack[i]);
}

}
}
Applications of Stack:

OTHER APPLICATIONS OF STACKS


❖ Recursion
1. Stack is used by compilers to check for balancing of
parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into
❖ Fibonacci series.
postfix/prefix form.
4. In recursion, all intermediate arguments and return values
are stored on the processor’s stack.
5. During a function call the return address and arguments
❖ Tower of Hanoi
are pushed onto a stack and on return they are popped off.

❖ Factorial
Recursion :
❖ Recursion is implemented using stack because activation records are to be stored in
LIFO order i.e. last in first out. An activation record of a function call contains three
parts: first is arguments, return address and local variables of the function.

❖ Recursion has many, many applications. In this module, we'll see how to use recursion
to compute the factorial function, to determine whether a word is a palindrome, to
compute powers of a number, to draw a type of fractal, and to solve the ancient
Towers of Hanoi problem
How recursion works?

void recurse()
... .. ...
recurse();
... .. ...
}

int main()
{
.. .. ...
recurse();
... .. ...
}
Advantages and Disadvantages of
Recursion

Recursion makes program elegant.


However, if performance is vital, use
loops instead as recursion is usually
much slower.

That being said, recursion is an important


concept. It is frequently used in data
structure and algorithms. For example, it
is common to use recursion in problems
such as tree traversal.
EXAMPLE OF RECURSION

Fibonacci series ://Important


❖ In computer science, the Fibonacci search technique is a
method of searching a sorted array using a divide and
conquer algorithm that narrows down possible locations
with the aid of Fibonacci numbers.

❖ Fibonacci search divides the array into two parts that have
sizes that are consecutive Fibonacci numbers. On average,
this leads to about 4% more comparisons to be executed,
but it has the advantage that one only needs addition and
subtraction to calculate the indices of the accessed array
elements, while classical binary search needs bit-shift
division or multiplication, operations that were less common
at the time Fibonacci search was first published. Fibonacci
search has an average- and worst-case complexity of O(log
n).
#include <stdio.h>

int fibbonacci(int n) { int main()

if(n == 0) {

{ int n = 5;

return 0; int i;

}
else if(n == 1) printf("Fibbonacci of %d: " , n);

{
return 1; for(i = 0;i<n;i++) {

} printf("%d ",fibbonacci(i));

Else }

{ }

return (fibbonacci(n-1) + fibbonacci(n-2));


}} Output
Fibbonacci of 5: 0 1 1 2 3
Example 2: factorial of a number using recursion
Example 2: Program to find the factorial of a number

#include <stdio.h>

int main()
int factorial(int n) {
{
//base case
int n = 5;
if(n == 0) {
int i;
return 1;
} else {
printf("Factorial of %d: %d\n" , n , factorial(n));
return n * factorial(n-1);
}
}
}
}

Output
Factorial of 5: 120
Example :3 Tower of Hanoi

Tower of Hanoi, is a mathematical puzzle which consists of


three towers (pegs) and more than one rings is as depicted −
These rings are of different sizes and stacked upon in an ascending order, i.e. the
smaller one sits over the larger one. There are other variations of the puzzle where
the number of disks increase, but the tower count remains the same.
Rules
The mission is to move all the disks to some another tower without violating the
sequence of arrangement. A few rules to be followed for Tower of Hanoi are −
•Only one disk can be moved among the towers at any given time.
•Only the "top" disk can be removed.
•No large disk can sit over a small disk.

Algorithm:
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
IMPORTANT QUESTIONS MODULE -4

1. Define Stack,Discuss the working and representation of a


Stack
2. Explain the Basic operations of Stack
3. Implement stack using Arrays
4. Implement stack using Pointers
5. Write the difference between arrays and Satcks
6. Discuss Tower of Hanoi problem
7. Explain the applications of stacks
8. write brief about recursion
9. what are the advantages and disadvantages of using stacks
10. Explain peek() function in stacks.
11. Illustrate the implementation of stack using arrays. ( Lab
program 8)
12. Write a c program to generate Fibonacci series using
recursion
13. Write a C program to find factorial of a number using
recursion

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy