SlideShare a Scribd company logo
1 of 45
VELAMMAL ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna University Chennai, & Approved by AICTE Delhi
Department of Computer Science and
Engineering
UNIT II - LINEARDATASTRUCTURES–
STACKS,QUEUES
Dr.M.Usha, AP
STACK:DEFINITION
Stack is a linear data structure which follows a
particular order in which the operations are
performed. The order may be LIFO(Last In First
Out) or FILO(First In Last Out).
WHY STACK?
Stack in PL:
– The return address (when the function is
complete it returns back to the function call)
– Arguments passed to the function
– Local variables of the function
Hardware Implementation of stack:
 consists of reserved contiguous region of
memory with a stack pointer into that memory.
The stack has a fixed location in memory at
which it begins.
The stack pointer is a hardware register that
points to the current extents of the stack.
WHY STACK?
Usage in Microprocessors
The stack shares the available RAM
memory with the heap and the static memory
area.
The C runtime library takes care of things
that need to be defined before the main()
function can be executed.
One of those things is setting up the stack
by loading the stack pointer register with the
start address of the stack.
Implementation of stack
The stack implementation can be done using
(i)Array :Array is a static data structure so the
collection of data must be fixed in size.
The only problem with this implementation is array
size must be specified initially.
struct stack
{
int stk[MAXSIZE];
int top;
};
• Implementation using Linked List :Linked
List is a dynamic data structure. So collection
of data can be used which are variable in size
and structure. The program executes can grow
and shrink to accommodate the data being
stored.
struct Node {
int data;
struct Node* link;
Drawback of Linked List implementation
• All the operations take constant time
• Calls to malloc and free are expensive
especially in comparison to the pointer
manipulation routines.
Limitation of Array Implementation:
The stack cannot grow and shrink dynamically
as per the requirement.
Operations on Stack
The basic operations on stack are
1.Push()
2.Pop()
Push() operation
• push() function is used to insert an element at the top
of the stack.
• The element is added to the stack container and the
size of the stack is increased by 1.
Before Performing Push() operation the stack condition
to be checked for overflow.
int isfull()
{
if(top == MAXSIZE)
return 1;
else
return 0;
}
STEP 1 START
STEP 2 Store the element to push into array
STEP 3 Check if top== (MAXSIZE-1) then stack is full else
goto step 4
STEP 4 Increment top as top = top+1
STEP 5 Add element to the position stk[top]=num
STEP 6 STOP
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error and exit.
• Step 3 − If the stack is not empty, accesses the data element
at which top is pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success. int pop()
{
int data;
if(!isempty())
{
data = stack[top];
top = top - 1;
return data;} else
{printf("Could not retrieve data, Stack is empty.n"); }}
Pop() operation
 Deletion of an element from the top of the stack is called pop
operation. The value of the variable top will be incremented by 1
whenever an item is deleted from the stack.
 The top most element of the stack is stored in an another variable
and then the top is decremented by 1.
 The operation returns the deleted value that was stored in another
variable as the result.
 Before performing pop() operation the stack condition must be
checked for underflow.
int isempty()
{
if(top == -1)
return 1;
else
return 0;
}
Program Execution
• https://www.tutorialspoint.com/data_structur
es_algorithms/stack_program_in_c.htm
Applications of Stack
– Evaluating Arithmetic Expression
– Conversion of infix to Postfix expression
– Backtracking Procedure
– During Function call and return Procedure
Evaluating Arithmetic
Expression
• Stack organized computers are better suited
for post-fix notation than the traditional infix
notation. Thus the infix notation must be
converted to the post-fix notation.
• Expressions are usually represented in what
is known as Infix notation, in which each
operator is written between two operands
(i.e., A + B).
• we must distinguish between ( A + B )*C
and A + ( B * C ) by using either parentheses
or some operator-precedence convention.
• Reverse Polish notation(postfix notation) –
It refers to the analogous notation in
which the operator is placed after its two
operands. Again, no parentheses is required in
Reverse Polish notation,
i.e., AB+
There are 3 levels of precedence for 5 binary
operators
Highest: Exponentiation (^)
Next highest: Multiplication (*) and division
(/)
Lowest: Addition (+) and Subtraction (-)
For ex:
Infix notation: (A-B)*[C/(D+E)+F]
Post-fix notation: AB- CDE +/F +*
• We first perform the arithmetic inside the
parentheses (A-B) and (D+E).
• The division of C/(D+E) must done prior to the
addition with F
• After that multiply the two terms inside the
parentheses and bracket.
The procedure for getting the result is:
• Convert the expression in Reverse Polish
notation( post-fix notation).
• Push the operands into the stack in the order
Infix notation: (2+4) * (4+6)
Post-fix notation: 2 4 + 4 6 + *
Result: 60
Conversion of infix to postfix
• Infix expression:The expression of the form a
op b. When an operator is in-between every
pair of operands.
• Postfix expression:The expression of the form
a b op. When an operator is followed for every
pair of operands.
• Why postfix representation of the expression?
The compiler scans the expression either
from left to right or from right to left.
• Consider the below expression: a op1 b op2
c op3 d
If op1 = +, op2 = *, op3 = +
The compiler first scans the expression to
evaluate the expression b * c, then again scan
the expression to add a to it.
The result is then added to d after another scan.
The repeated scanning makes it very in-
efficient.
• It is better to convert the expression to
postfix(or prefix) form before evaluation.
Algorithm
• 1. Scan the infix expression from left to right.
• 2. If the scanned character is an operand, output it.
• 3. Else,
…..3.1 If the precedence of the scanned operator is
greater than the precedence of the operator in the stack(or
the stack is empty or the stack contains a ‘(‘ ), push it.
…..3.2 Else, Pop all the operators from the stack which
are greater than or equal to in precedence than that of the
scanned operator. After doing that Push the scanned
operator to the stack. (If you encounter parenthesis while
popping then stop there and push the scanned operator in
the stack.)
• 4. If the scanned character is an ‘(‘, push it to the stack.
• 5. If the scanned character is an ‘)’, pop the stack and and
output it until a ‘(‘ is encountered, and discard both the
parenthesis.
Linked List Implementation -
Initial Stack
Linked List Implementation-
Push()
void pop()
{
struct Node* temp;
if (top == NULL) {
printf("nStack Underflow“);
exit(1);
}
else {
temp = top;
top = top->link;
temp->link = NULL;
free(temp);
}
}
Queue ADT
Mrs. G. Sumathi
Assistant Professor
Velammal Engineering College
Chennai
Agenda
• Queue ADT
• Array implementation of queue
• Linked list implementation of queue
• Types
– Circular Queue
– Double Ended Queue
– Priority Queue
• Applications of Queue
Queue ADT
• Linear data structure
• Insertion occurs only at one end called rear
• Deletion occurs only at one end called front
• Element that is inserted first is deleted (FIFO
principle)
Operations in queue:
• Enqueue: Inserting an element into the queue (at
rear)
• Dequeue: Deleting an element from the queue (at
front)
Exceptional Conditions:
• Overflow: Attempting to insert an element into
queue when it is full
• Underflow: Attempting to delete an element from
queue when it is empty
Queue ADT
Array Implementation of Queue
Enqueue operation
Void Enqueue (int num) //Let num = 12 and max=5
{
if (rear==max-1)
print(“Queue Overlfow”);
else if (front == -1 && rear == -1)
{
front = rear = 0;
Q[rear] = num;
}
else
{
rear++;
Q[rear] = num;
}
}
12 25 18
Dequeue Operation
Void Dequeue()
{
int val;
if (front == -1 || front > rear)
print(“Queue Underflow”);
else
{
val= Q[front];
front++;
}
}
10 20 30
Display Operation
void Display ()
{
int i;
if (front == -1 || front > rear)
print (“Queue Underflow”);
else
{
for(i=front; i<=rear; i++)
print(Q[i]);
}
}
Linked List Implementation of Queue
Enqueue operation
void Enqueue (int num)
{
n=(struct node *) malloc (sizeof (struct node));
ndata=num;
nnext=NULL;
if(rear == NULL)
front = rear= n;
else
{
rearnext = n;
rear = n;
}
}
Dequeue Operation
Void Dequeue()
{
struct node *t;
if (front == NULL)
print(“Underflow”);
else
{
t = front;
front = front  next;
free(t);
}
}
Circular Queue
• Type of queue
• Last position of the queue is connected to the first
position in a circular fashion
• Overcome the disadvantage of wastage of front end
memory space after performing dequeue operation
in linear queue
• In linear queue, after performing dequeue,
the memory space at the front end remains
unused
• This situation does not occur in circular queue
Need for Circular Queue
Enqueue Operation
void Cir_Enqueue (int num)
{
if((front == 0 && rear == max-1) || (rear ==(front-1)))
print(“Queue Overflow”);
else if (front == -1 && rear == -1)
{ front = rear = 0;
Q[rear] = num;
}
else if (rear == max-1 && front != 0)
{ rear = 0;
Q[rear] = num;
}
else
{ rear ++;
Q[rear] = num;
}
}
30
40
50 60
70
Dequeue Operation
Void Cir_Dequeue()
{
int val;
if (front ==-1)
print (“Queue Underflow”);
val = Q[front];
if (front == rear)
front = rear = – 1;
else if (front == max – 1)
front = 0;
else
front ++;
}
20
40
20
30
20
30
40
Double Ended Queue (DEQUE)
DEQUE is of two types
• Input restricted DEQUE
– Insertion at only one end
– Deletion at both ends
• Output restricted DEQUE
– Deletion at only one end
– Insertion at both ends
Priority Queue
• Every item has a priority associated with it
• Element with higher priority is served first
• If two elements have same priority then they served
according to the order in the queue
• Generally, the value of the element itself is
considered as higher priority
• Applications:
– CPU scheduling
– Graph algorithms like Dijkstra’s shortest path, Prim’s
minimum spanning tree, etc,.
Applications of Queue
• Data getting transferred between the IO Buffers
(Input Output Buffers).
• CPU scheduling and Disk scheduling.
• Managing shared resources between various
processes.
• Job scheduling
• Traffic light functioning is the best example
for circular queues . The colors in the traffic light
follow a circular pattern.
• In page replacement algorithms, a circular list of
pages is maintained and when a page needs to be
replaced, the page in the front of the queue will be
chosen.
Applications of Circular Queue
Queries??
Thank You !!!

More Related Content

What's hot

Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Binary search tree
Binary search treeBinary search tree
Binary search treeKousalya M
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applicationssomendra kumar
 
Queue data structure
Queue data structureQueue data structure
Queue data structureanooppjoseph
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First SearchKevin Jadiya
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Muhammad Hammad Waseem
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queueSrajan Shukla
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)Elavarasi K
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy TutorialAfzal Badshah
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search treeKrish_ver2
 
Insertion sort
Insertion sortInsertion sort
Insertion sortalmaqboli
 
Queue implementation
Queue implementationQueue implementation
Queue implementationRajendran
 

What's hot (20)

Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Red black tree
Red black treeRed black tree
Red black tree
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Conceptual Data Modeling
Conceptual Data ModelingConceptual Data Modeling
Conceptual Data Modeling
 
Queue
QueueQueue
Queue
 

Similar to Unit II - LINEAR DATA STRUCTURES

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxchandankumar364348
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxYogesh Pawar
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxApplication of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxPrakash Zodge
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2SSE_AndyLi
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxprakashvs7
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 

Similar to Unit II - LINEAR DATA STRUCTURES (20)

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
Stacks
StacksStacks
Stacks
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
stack & queue
stack & queuestack & queue
stack & queue
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxApplication of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Unit 4 queue
Unit   4 queueUnit   4 queue
Unit 4 queue
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 

Recently uploaded

Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 

Recently uploaded (20)

Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

Unit II - LINEAR DATA STRUCTURES

  • 1. VELAMMAL ENGINEERING COLLEGE An Autonomous Institution, Affiliated to Anna University Chennai, & Approved by AICTE Delhi Department of Computer Science and Engineering UNIT II - LINEARDATASTRUCTURES– STACKS,QUEUES Dr.M.Usha, AP
  • 2. STACK:DEFINITION Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
  • 3. WHY STACK? Stack in PL: – The return address (when the function is complete it returns back to the function call) – Arguments passed to the function – Local variables of the function Hardware Implementation of stack:  consists of reserved contiguous region of memory with a stack pointer into that memory. The stack has a fixed location in memory at which it begins. The stack pointer is a hardware register that points to the current extents of the stack.
  • 4. WHY STACK? Usage in Microprocessors The stack shares the available RAM memory with the heap and the static memory area. The C runtime library takes care of things that need to be defined before the main() function can be executed. One of those things is setting up the stack by loading the stack pointer register with the start address of the stack.
  • 5. Implementation of stack The stack implementation can be done using (i)Array :Array is a static data structure so the collection of data must be fixed in size. The only problem with this implementation is array size must be specified initially. struct stack { int stk[MAXSIZE]; int top; };
  • 6. • Implementation using Linked List :Linked List is a dynamic data structure. So collection of data can be used which are variable in size and structure. The program executes can grow and shrink to accommodate the data being stored. struct Node { int data; struct Node* link;
  • 7. Drawback of Linked List implementation • All the operations take constant time • Calls to malloc and free are expensive especially in comparison to the pointer manipulation routines. Limitation of Array Implementation: The stack cannot grow and shrink dynamically as per the requirement.
  • 8. Operations on Stack The basic operations on stack are 1.Push() 2.Pop()
  • 9. Push() operation • push() function is used to insert an element at the top of the stack. • The element is added to the stack container and the size of the stack is increased by 1. Before Performing Push() operation the stack condition to be checked for overflow. int isfull() { if(top == MAXSIZE) return 1; else return 0; }
  • 10. STEP 1 START STEP 2 Store the element to push into array STEP 3 Check if top== (MAXSIZE-1) then stack is full else goto step 4 STEP 4 Increment top as top = top+1 STEP 5 Add element to the position stk[top]=num STEP 6 STOP
  • 11. • Step 1 − Checks if the stack is empty. • Step 2 − If the stack is empty, produces an error and exit. • Step 3 − If the stack is not empty, accesses the data element at which top is pointing. • Step 4 − Decreases the value of top by 1. • Step 5 − Returns success. int pop() { int data; if(!isempty()) { data = stack[top]; top = top - 1; return data;} else {printf("Could not retrieve data, Stack is empty.n"); }}
  • 12. Pop() operation  Deletion of an element from the top of the stack is called pop operation. The value of the variable top will be incremented by 1 whenever an item is deleted from the stack.  The top most element of the stack is stored in an another variable and then the top is decremented by 1.  The operation returns the deleted value that was stored in another variable as the result.  Before performing pop() operation the stack condition must be checked for underflow. int isempty() { if(top == -1) return 1; else return 0; }
  • 14. Applications of Stack – Evaluating Arithmetic Expression – Conversion of infix to Postfix expression – Backtracking Procedure – During Function call and return Procedure
  • 15. Evaluating Arithmetic Expression • Stack organized computers are better suited for post-fix notation than the traditional infix notation. Thus the infix notation must be converted to the post-fix notation. • Expressions are usually represented in what is known as Infix notation, in which each operator is written between two operands (i.e., A + B). • we must distinguish between ( A + B )*C and A + ( B * C ) by using either parentheses or some operator-precedence convention.
  • 16. • Reverse Polish notation(postfix notation) – It refers to the analogous notation in which the operator is placed after its two operands. Again, no parentheses is required in Reverse Polish notation, i.e., AB+ There are 3 levels of precedence for 5 binary operators Highest: Exponentiation (^) Next highest: Multiplication (*) and division (/) Lowest: Addition (+) and Subtraction (-)
  • 17. For ex: Infix notation: (A-B)*[C/(D+E)+F] Post-fix notation: AB- CDE +/F +* • We first perform the arithmetic inside the parentheses (A-B) and (D+E). • The division of C/(D+E) must done prior to the addition with F • After that multiply the two terms inside the parentheses and bracket. The procedure for getting the result is: • Convert the expression in Reverse Polish notation( post-fix notation). • Push the operands into the stack in the order
  • 18. Infix notation: (2+4) * (4+6) Post-fix notation: 2 4 + 4 6 + * Result: 60
  • 19. Conversion of infix to postfix • Infix expression:The expression of the form a op b. When an operator is in-between every pair of operands. • Postfix expression:The expression of the form a b op. When an operator is followed for every pair of operands. • Why postfix representation of the expression? The compiler scans the expression either from left to right or from right to left.
  • 20. • Consider the below expression: a op1 b op2 c op3 d If op1 = +, op2 = *, op3 = + The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it. The result is then added to d after another scan. The repeated scanning makes it very in- efficient. • It is better to convert the expression to postfix(or prefix) form before evaluation.
  • 21. Algorithm • 1. Scan the infix expression from left to right. • 2. If the scanned character is an operand, output it. • 3. Else, …..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it. …..3.2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) • 4. If the scanned character is an ‘(‘, push it to the stack. • 5. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the parenthesis.
  • 22.
  • 23.
  • 24. Linked List Implementation - Initial Stack
  • 26. void pop() { struct Node* temp; if (top == NULL) { printf("nStack Underflow“); exit(1); } else { temp = top; top = top->link; temp->link = NULL; free(temp); } }
  • 27. Queue ADT Mrs. G. Sumathi Assistant Professor Velammal Engineering College Chennai
  • 28. Agenda • Queue ADT • Array implementation of queue • Linked list implementation of queue • Types – Circular Queue – Double Ended Queue – Priority Queue • Applications of Queue
  • 29. Queue ADT • Linear data structure • Insertion occurs only at one end called rear • Deletion occurs only at one end called front • Element that is inserted first is deleted (FIFO principle)
  • 30. Operations in queue: • Enqueue: Inserting an element into the queue (at rear) • Dequeue: Deleting an element from the queue (at front) Exceptional Conditions: • Overflow: Attempting to insert an element into queue when it is full • Underflow: Attempting to delete an element from queue when it is empty Queue ADT
  • 31. Array Implementation of Queue Enqueue operation Void Enqueue (int num) //Let num = 12 and max=5 { if (rear==max-1) print(“Queue Overlfow”); else if (front == -1 && rear == -1) { front = rear = 0; Q[rear] = num; } else { rear++; Q[rear] = num; } } 12 25 18
  • 32. Dequeue Operation Void Dequeue() { int val; if (front == -1 || front > rear) print(“Queue Underflow”); else { val= Q[front]; front++; } } 10 20 30
  • 33. Display Operation void Display () { int i; if (front == -1 || front > rear) print (“Queue Underflow”); else { for(i=front; i<=rear; i++) print(Q[i]); } }
  • 34. Linked List Implementation of Queue Enqueue operation void Enqueue (int num) { n=(struct node *) malloc (sizeof (struct node)); ndata=num; nnext=NULL; if(rear == NULL) front = rear= n; else { rearnext = n; rear = n; } }
  • 35. Dequeue Operation Void Dequeue() { struct node *t; if (front == NULL) print(“Underflow”); else { t = front; front = front  next; free(t); } }
  • 36. Circular Queue • Type of queue • Last position of the queue is connected to the first position in a circular fashion • Overcome the disadvantage of wastage of front end memory space after performing dequeue operation in linear queue
  • 37. • In linear queue, after performing dequeue, the memory space at the front end remains unused • This situation does not occur in circular queue Need for Circular Queue
  • 38. Enqueue Operation void Cir_Enqueue (int num) { if((front == 0 && rear == max-1) || (rear ==(front-1))) print(“Queue Overflow”); else if (front == -1 && rear == -1) { front = rear = 0; Q[rear] = num; } else if (rear == max-1 && front != 0) { rear = 0; Q[rear] = num; } else { rear ++; Q[rear] = num; } } 30 40 50 60 70
  • 39. Dequeue Operation Void Cir_Dequeue() { int val; if (front ==-1) print (“Queue Underflow”); val = Q[front]; if (front == rear) front = rear = – 1; else if (front == max – 1) front = 0; else front ++; } 20 40 20 30 20 30 40
  • 40. Double Ended Queue (DEQUE) DEQUE is of two types • Input restricted DEQUE – Insertion at only one end – Deletion at both ends • Output restricted DEQUE – Deletion at only one end – Insertion at both ends
  • 41. Priority Queue • Every item has a priority associated with it • Element with higher priority is served first • If two elements have same priority then they served according to the order in the queue • Generally, the value of the element itself is considered as higher priority • Applications: – CPU scheduling – Graph algorithms like Dijkstra’s shortest path, Prim’s minimum spanning tree, etc,.
  • 42. Applications of Queue • Data getting transferred between the IO Buffers (Input Output Buffers). • CPU scheduling and Disk scheduling. • Managing shared resources between various processes. • Job scheduling
  • 43. • Traffic light functioning is the best example for circular queues . The colors in the traffic light follow a circular pattern. • In page replacement algorithms, a circular list of pages is maintained and when a page needs to be replaced, the page in the front of the queue will be chosen. Applications of Circular Queue

Editor's Notes

  1. Data compression : It is used in Huffman codes which is used to compresses data. Artificial Intelligence : A* Search Algorithm : The A* search algorithm finds the shortest path between two vertices of a weighted graph, trying out the most promising routes first. The priority queue (also known as the fringe) is used to keep track of unexplored routes, the one for which a lower bound on the total path length is smallest is given highest priority.
  2. Pallindrome checker. A-steal job scheduling algorithm      - The A-steal algorithm implements task scheduling for multiple processors (multiprocessor scheduling).      - The processor gets the first element from the double ended queue.      - When one of the processors completes execution of its own thread, it can steal a thread from other processors.      - It gets the last element from the deque of another processor and executes it. Undo-redo operations in software applications.