SlideShare a Scribd company logo
A Brief Introduction to Stacks
Urjit Patel
MNNIT,Allahabad
August 30, 2015
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 1 / 26
Index
What is Stack?
Understanding LIFO
Basic operations used in stack
Implementation of stack using array and linked list
Advantages of stack
Application
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 2 / 26
What is Stack?
Figure: Basic model of stack
In computer science, a stack or LIFO (last in, first out) is an abstract data
type that serves as a collection of elements, with two principal operations:
push, which adds an element to the collection, and pop, which removes the
last element that was added.
It is an ordered group of homogeneous items of elements.
Elements are added to and removed from the top of the stack (the most
recently added items are at the top of the stack). Refer Figure:1.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 3 / 26
What is Stack? (Contd.)
A stack is a restricted data structure, because only a small number of
operations are performed on it.
The nature of the pop and push operations also means that stack elements
have a natural order.
Elements are removed from the stack in the reverse order to the order of their
addition.
Now we will discuss Stack in detail but before that lets understand the term
LIFO.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 4 / 26
Understanding LIFO
Stack is also know as LIFO.
The term LIFO stands for LAST IN FIRST OUT.
The basic concept can be illustrated by thinking of your LIFO set as a stack
of plates or books where you can only take the top item off the stack in order
to remove things from it.
Your cannot remove a book placed in between without removing the books
placed on top of it.this is basic principle used behind stacks.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 5 / 26
Basic operations used in stack
Push
Push inserts an element at top of the stack.
Pop
Pop deletes the element placed at the top of the stack.
isEmpty
isEmpty checks whether the stack is empty or not.
isFull
isFull checks whether the stack is full or not.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 6 / 26
Implementation
Since stack is a linear list, it can be implemented using arrays or linked lists.
In the next two sections we will study the two implementations of stack.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 7 / 26
Using Array
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 8 / 26
Push (Using array)
Function-Adds an element at the top of the stack.
Precondition-Stack has been initialized and is not full.
Post-condition-newItem is at the top of the stack.
void push(int item)
{
if isFull () then
{
printf (”StackOverflow n”);
return;
}
end if
top = top + 1;
stack [top] = item;
}
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 9 / 26
Pop (Using array)
Function-Removes topItem from stack and returns it in item.
Precondition-Stack has been initialized and is not empty.
Post-condition-Top element has been removed from stack and item is a
copy of the removed element.
int pop()
{
intitem;
if isEmpty () then
{
printf (”StackUnderflow n”);
exit (1) ;
}
end if
item = stack [arr] ;
top = top − 1;
return item;
}
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 10 / 26
isEmpty (Using array)
Function-Checks whether the stack is empty or not.
Post-condition-returns true if empty or else false.
int isEmpty()
{
if (top == −1) then
return 1;
else
return 0;
end if
}
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 11 / 26
isFull (Using array)
Function-Checks whether the stack is full or not.
Post-condition-returns true if full or else false.
int isFull()
{
if (top == MAX − 1) then
return 1;
else
return 0;
end if
}
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 12 / 26
Review
Stack using array
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 13 / 26
Using Linked Lists
When the size of stack is not known in advance, it is better to implement
linked list.
We will take a single linked list so the structure of the node would be-
struct node {
int info;
struct node *link;
};
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 14 / 26
Push (Using Linked List)
Function-Adds an element at the top of the stack.
Precondition-Stack has been initialized and is not full.
Post-condition-newItem is at the top of the stack.
void push(int item)
{
struct node *tmp;
tmp= (stuct node ∗) malloc (struct node);
if tmp == NULL then
{
printf (”StackOverflow n”);
return;
}
end if
tmp → info = item;
tmp → link = top;
top = tmp;
}
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 15 / 26
Pop (Using Linked List)
Function-Removes topItem from stack and returns it in item.
Precondition-Stack has been initialized and is not empty.
Post-condition-Top element has been removed from stack and item is a
copy of the removed element.
int pop()
{
struct node *tmp;
if isEmpty () then
{
printf (”Stack Underflow n”);
exit (1)
}
end if
tmp = top;
item = tmp → info;
top = tmp → link;
free (tmp) ;
return item;Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 16 / 26
isEmpty (Using Linked List)
Function-Checks whether the stack is empty or not.
Post-condition-returns true if empty or else false.
int isEmpty()
{
if (top == NULL) then
return 1;
else
return 0;
end if
}
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 17 / 26
Array vs Linked List
Array Linked List
Accessing
Stack elements
can be randomly
Accessed using
Subscript Variable
While In Linked List
We have to Traverse
Through the Linked
List for Accessing El-
ement.
Memory Structure
The stack elements
are stored at con-
tiguous memory.
The stack elements
are stored at dif-
ferent memory lo-
cations but joined
through pointers.
Insertion deletion
As the Array ele-
ments are stored in
Consecutive memory
Locations so While
Inserting elements
we have to create
space for Insertion.
While in linked list
one has to only
change the pointers.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 18 / 26
Array vs Linked List (Contd.)
Array Linked List
Memory Allocation
Memory Should
be allocated at
Compile-Time in ar-
ray . i.e at the time
when Programmer
is Writing Program.
In Linked list mem-
ory can be allocated
at Run-Time , i.e
After executing Pro-
gram
Allocation type
Stack uses Static
Memory Allocation
While linked list uses
dynamic memory al-
location
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 19 / 26
Application of stack
The various application are
Reversing of string
Conversion of infix forms to postfix forms.
Check well-formed paranthesis.
Used in compilers to check the syntax whether is it correct or not.
We shall discuss some applications now.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 20 / 26
Reverse a string using stack
The basic procedure is simple.
First push each character of string into the stack.
Then pop each character out of the stack.
The resultant would be the reversed string.
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 21 / 26
Pseudo Code for reversal
main()
{
char str[20];
int i;
printf(”Enter string:”);
gets(str);
while i < strlen (str) do
push(str[i]);
i++;
end while
while i < strlen (str) do
str[i]=pop();
i++;
end while
printf(”The reversed string is”);
puts(str);
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 22 / 26
Evaluation of postfix expression using stack
The steps involved to evaluate the postfix expression are-
Scan the symbol of array postfix one by one from left to right
If symbol is operand , we push it in stack.
If the symbol is operator , we pop two elements from stack and apply the
operator to these two elements.
push the result on the stack.
Lets understand with an example.
Example:-3 ∗ (4 + 5)/2 → 345 + ∗2 → 13
Remaining postfix string int stack(top)
345 + ∗2/ empty
45 + ∗2/ 3
5 + ∗2/ 3 4
+ ∗ 2/ 3 4 5
*2/ 3 9
2/ 27
/ 27 2
NULL 13 ← ans
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 23 / 26
Pseudo Code for evaluating post expressions
long int evalpost()
{
long int a,b,temp,result;
unsigned int i;
while i < strlen (postfix) do
if postfix [i] ≤ 9 then
push (postfix [i] − 0 );
else
a=pop();
b=pop();
switch(postfix[i])
case + : temp = b + a; break;
case − : temp = b − a; break;
case ∗ : temp = b ∗ a; break;
case / : temp = b/a; break;
case % : temp = b%a; break;
case : temp = pow(a, b); break;
}
end ifUrjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 24 / 26
Pseudo Code for evaluating post expressions
}
push(temp);
}
}
result=pop();
return result;
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 25 / 26
The End
Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 26 / 26

More Related Content

What's hot

STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
Yaksh Jethva
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
Trupti Agrawal
 
computer notes - List implementation
computer notes - List implementationcomputer notes - List implementation
computer notes - List implementation
ecomputernotes
 
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
Gianluca Amato
 
Data structures
Data structuresData structures
Data structures
Sneha Chopra
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
iqbalphy1
 
Excel formula
Excel formulaExcel formula
Excel formula
VedPrakashMishra15
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrms
Misssaxena
 
Stacks
StacksStacks
Data structures &amp; algorithms
Data structures &amp; algorithmsData structures &amp; algorithms
Data structures &amp; algorithms
Prabhu R
 
Purely functional data structures demystified
Purely functional data structures demystifiedPurely functional data structures demystified
Purely functional data structures demystified
Mohit Thatte
 
Simple Linear Regression with R
Simple Linear Regression with RSimple Linear Regression with R
Simple Linear Regression with R
Jerome Gomes
 
Module System in Standard ML
Module System in Standard MLModule System in Standard ML
Module System in Standard ML
Keheliya Gallaba
 
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting AlgorithmComparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
paperpublications3
 

What's hot (14)

STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
 
computer notes - List implementation
computer notes - List implementationcomputer notes - List implementation
computer notes - List implementation
 
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
 
Data structures
Data structuresData structures
Data structures
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Excel formula
Excel formulaExcel formula
Excel formula
 
Searching techniques with progrms
Searching techniques with progrmsSearching techniques with progrms
Searching techniques with progrms
 
Stacks
StacksStacks
Stacks
 
Data structures &amp; algorithms
Data structures &amp; algorithmsData structures &amp; algorithms
Data structures &amp; algorithms
 
Purely functional data structures demystified
Purely functional data structures demystifiedPurely functional data structures demystified
Purely functional data structures demystified
 
Simple Linear Regression with R
Simple Linear Regression with RSimple Linear Regression with R
Simple Linear Regression with R
 
Module System in Standard ML
Module System in Standard MLModule System in Standard ML
Module System in Standard ML
 
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting AlgorithmComparative Performance Analysis & Complexity of Different Sorting Algorithm
Comparative Performance Analysis & Complexity of Different Sorting Algorithm
 

Similar to Stacks

VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
skilljiolms
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
SeethaDinesh
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
SeethaDinesh
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
SeethaDinesh
 
Stack and queue
Stack and queueStack and queue
Stack and queue
CHANDAN KUMAR
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
Pulkitmodi1998
 
Data structures1
Data structures1Data structures1
Data structures1
Parthipan Parthi
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
V.V.Vanniaperumal College for Women
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
EktaVaswani2
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
SonaPathak4
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
Balwant Gorad
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
SajalFayyaz
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
poongothai11
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
Rai University
 
AD3251-LINKED LIST,STACK ADT,QUEUE ADT.docx
AD3251-LINKED LIST,STACK ADT,QUEUE ADT.docxAD3251-LINKED LIST,STACK ADT,QUEUE ADT.docx
AD3251-LINKED LIST,STACK ADT,QUEUE ADT.docx
AmuthachenthiruK
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptxSTACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
sunitha1792
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma
 

Similar to Stacks (20)

VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
Data structures1
Data structures1Data structures1
Data structures1
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Data Structure.pptx
Data Structure.pptxData Structure.pptx
Data Structure.pptx
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operationsStack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
AD3251-LINKED LIST,STACK ADT,QUEUE ADT.docx
AD3251-LINKED LIST,STACK ADT,QUEUE ADT.docxAD3251-LINKED LIST,STACK ADT,QUEUE ADT.docx
AD3251-LINKED LIST,STACK ADT,QUEUE ADT.docx
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptxSTACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
STACK AND QUEUE CIRCULAR QUEUE PPTS.pptx
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 

More from Shivam Singh

Trees
TreesTrees
What If Microsoft sold diapers!? MS Diapers!
What If Microsoft sold diapers!? MS Diapers!What If Microsoft sold diapers!? MS Diapers!
What If Microsoft sold diapers!? MS Diapers!
Shivam Singh
 
Search Algprithms
Search AlgprithmsSearch Algprithms
Search Algprithms
Shivam Singh
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Shivam Singh
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
Shivam Singh
 
Linked List
Linked ListLinked List
Linked List
Shivam Singh
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Shivam Singh
 

More from Shivam Singh (7)

Trees
TreesTrees
Trees
 
What If Microsoft sold diapers!? MS Diapers!
What If Microsoft sold diapers!? MS Diapers!What If Microsoft sold diapers!? MS Diapers!
What If Microsoft sold diapers!? MS Diapers!
 
Search Algprithms
Search AlgprithmsSearch Algprithms
Search Algprithms
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
 
Linked List
Linked ListLinked List
Linked List
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 

Recently uploaded

The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
Aditya Rajan Patra
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 

Recently uploaded (20)

The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 

Stacks

  • 1. A Brief Introduction to Stacks Urjit Patel MNNIT,Allahabad August 30, 2015 Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 1 / 26
  • 2. Index What is Stack? Understanding LIFO Basic operations used in stack Implementation of stack using array and linked list Advantages of stack Application Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 2 / 26
  • 3. What is Stack? Figure: Basic model of stack In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added. It is an ordered group of homogeneous items of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). Refer Figure:1. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 3 / 26
  • 4. What is Stack? (Contd.) A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also means that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition. Now we will discuss Stack in detail but before that lets understand the term LIFO. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 4 / 26
  • 5. Understanding LIFO Stack is also know as LIFO. The term LIFO stands for LAST IN FIRST OUT. The basic concept can be illustrated by thinking of your LIFO set as a stack of plates or books where you can only take the top item off the stack in order to remove things from it. Your cannot remove a book placed in between without removing the books placed on top of it.this is basic principle used behind stacks. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 5 / 26
  • 6. Basic operations used in stack Push Push inserts an element at top of the stack. Pop Pop deletes the element placed at the top of the stack. isEmpty isEmpty checks whether the stack is empty or not. isFull isFull checks whether the stack is full or not. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 6 / 26
  • 7. Implementation Since stack is a linear list, it can be implemented using arrays or linked lists. In the next two sections we will study the two implementations of stack. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 7 / 26
  • 8. Using Array Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 8 / 26
  • 9. Push (Using array) Function-Adds an element at the top of the stack. Precondition-Stack has been initialized and is not full. Post-condition-newItem is at the top of the stack. void push(int item) { if isFull () then { printf (”StackOverflow n”); return; } end if top = top + 1; stack [top] = item; } Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 9 / 26
  • 10. Pop (Using array) Function-Removes topItem from stack and returns it in item. Precondition-Stack has been initialized and is not empty. Post-condition-Top element has been removed from stack and item is a copy of the removed element. int pop() { intitem; if isEmpty () then { printf (”StackUnderflow n”); exit (1) ; } end if item = stack [arr] ; top = top − 1; return item; } Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 10 / 26
  • 11. isEmpty (Using array) Function-Checks whether the stack is empty or not. Post-condition-returns true if empty or else false. int isEmpty() { if (top == −1) then return 1; else return 0; end if } Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 11 / 26
  • 12. isFull (Using array) Function-Checks whether the stack is full or not. Post-condition-returns true if full or else false. int isFull() { if (top == MAX − 1) then return 1; else return 0; end if } Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 12 / 26
  • 13. Review Stack using array Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 13 / 26
  • 14. Using Linked Lists When the size of stack is not known in advance, it is better to implement linked list. We will take a single linked list so the structure of the node would be- struct node { int info; struct node *link; }; Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 14 / 26
  • 15. Push (Using Linked List) Function-Adds an element at the top of the stack. Precondition-Stack has been initialized and is not full. Post-condition-newItem is at the top of the stack. void push(int item) { struct node *tmp; tmp= (stuct node ∗) malloc (struct node); if tmp == NULL then { printf (”StackOverflow n”); return; } end if tmp → info = item; tmp → link = top; top = tmp; } Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 15 / 26
  • 16. Pop (Using Linked List) Function-Removes topItem from stack and returns it in item. Precondition-Stack has been initialized and is not empty. Post-condition-Top element has been removed from stack and item is a copy of the removed element. int pop() { struct node *tmp; if isEmpty () then { printf (”Stack Underflow n”); exit (1) } end if tmp = top; item = tmp → info; top = tmp → link; free (tmp) ; return item;Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 16 / 26
  • 17. isEmpty (Using Linked List) Function-Checks whether the stack is empty or not. Post-condition-returns true if empty or else false. int isEmpty() { if (top == NULL) then return 1; else return 0; end if } Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 17 / 26
  • 18. Array vs Linked List Array Linked List Accessing Stack elements can be randomly Accessed using Subscript Variable While In Linked List We have to Traverse Through the Linked List for Accessing El- ement. Memory Structure The stack elements are stored at con- tiguous memory. The stack elements are stored at dif- ferent memory lo- cations but joined through pointers. Insertion deletion As the Array ele- ments are stored in Consecutive memory Locations so While Inserting elements we have to create space for Insertion. While in linked list one has to only change the pointers. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 18 / 26
  • 19. Array vs Linked List (Contd.) Array Linked List Memory Allocation Memory Should be allocated at Compile-Time in ar- ray . i.e at the time when Programmer is Writing Program. In Linked list mem- ory can be allocated at Run-Time , i.e After executing Pro- gram Allocation type Stack uses Static Memory Allocation While linked list uses dynamic memory al- location Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 19 / 26
  • 20. Application of stack The various application are Reversing of string Conversion of infix forms to postfix forms. Check well-formed paranthesis. Used in compilers to check the syntax whether is it correct or not. We shall discuss some applications now. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 20 / 26
  • 21. Reverse a string using stack The basic procedure is simple. First push each character of string into the stack. Then pop each character out of the stack. The resultant would be the reversed string. Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 21 / 26
  • 22. Pseudo Code for reversal main() { char str[20]; int i; printf(”Enter string:”); gets(str); while i < strlen (str) do push(str[i]); i++; end while while i < strlen (str) do str[i]=pop(); i++; end while printf(”The reversed string is”); puts(str); Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 22 / 26
  • 23. Evaluation of postfix expression using stack The steps involved to evaluate the postfix expression are- Scan the symbol of array postfix one by one from left to right If symbol is operand , we push it in stack. If the symbol is operator , we pop two elements from stack and apply the operator to these two elements. push the result on the stack. Lets understand with an example. Example:-3 ∗ (4 + 5)/2 → 345 + ∗2 → 13 Remaining postfix string int stack(top) 345 + ∗2/ empty 45 + ∗2/ 3 5 + ∗2/ 3 4 + ∗ 2/ 3 4 5 *2/ 3 9 2/ 27 / 27 2 NULL 13 ← ans Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 23 / 26
  • 24. Pseudo Code for evaluating post expressions long int evalpost() { long int a,b,temp,result; unsigned int i; while i < strlen (postfix) do if postfix [i] ≤ 9 then push (postfix [i] − 0 ); else a=pop(); b=pop(); switch(postfix[i]) case + : temp = b + a; break; case − : temp = b − a; break; case ∗ : temp = b ∗ a; break; case / : temp = b/a; break; case % : temp = b%a; break; case : temp = pow(a, b); break; } end ifUrjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 24 / 26
  • 25. Pseudo Code for evaluating post expressions } push(temp); } } result=pop(); return result; Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 25 / 26
  • 26. The End Urjit Patel (MNNIT,Allahabad) Stacks August 30, 2015 26 / 26