SlideShare a Scribd company logo
1 of 41
Download to read offline
Lecture 5



• Stack (Array Implementation)
• Queue (Array Implementation )




                FIST, Multi Media University
Stack
What is a Stack?

  1) It is a data structure for storing some values
  2) It is an ADT.
  3) Implemented using Arrays or Linked List
  4) used in Operating System and in System
    Programming


                     FIST, Multi Media University
Stack
How to Store and Retrieve from a Stack?
 1) All Insertions ( Storing) and Deletions (Removing)
 of entries are made at one end called the TOP of Stack
 2) Last item added to a stack (PUSH) is always the first
 that will be removed (POP) from the stack.
 3) This property is called Last In First Out also known
 as LIFO
 4) The operations are done with a single pointer to the
 top of list of elements.
                    FIST, Multi Media University Operations...
Stack



    E                                       TOP
F
    D
                          EG - Plates
G
    C                              Books
    B                              (LIFO)
    A
    FIST, Multi Media University
Operations
• There are Four operations :
     1) Push ( )
             used to add the data at the top of the stack.
             Check whether the stack is full or not
     2) Pop ( )
             used to remove data at the top of the stack.
             Check whether the stack is empty or not
     3) Empty ( )
             Checks whether stack is empty, TOP = -1
     4) Full ( )
             checks whether stackUniversity TOP = maxstacksize
                       FIST, Multi Media
                                         is full,
Stack - implementation

• Uses ARRAY to represent a stack
  Class stack
  { private :
      int stackelement[10],TOP;
    public:
             stack( ) { top = -1}               int Empty( );
             void push(int);                    int Full ( );
             int Pop( ); Multi Media University };
                       FIST,
Stack

How to Push?
  Void stack :: Push(int data2add)
  { if (!Full( ))
     { TOP++;
       Stackelement[TOP] = data2add;
     }
     else
             cout << “Stack is Full!!!”<<endl;
  }                FIST, Multi Media University
Stack
How to Pop?
  Int stack :: Pop( )
  {int data2remove;
   if (!Empty( ))
        { data2remove = Stackelement[TOP];
          TOP--; return data2remove; }
    else{ cout << “Stack is Empty!!!”<<endl;
            return 0;
        } }
                  FIST, Multi Media University
Stack
How to check for full?
 Int Stack :: Full( )
 {
     if (TOP==9) return 1;
     else return 0;
 }


                 FIST, Multi Media University
Stack

How to check for Empty?
 Int Stack :: Empty( )
 {
    if (TOP== -1) return 1;
    else return 0;
 }

              FIST, Multi Media University
Stack

Void main( )
{                                 stackobj.Push(55);
stack stackobj;                   cout << stackobj.Pop( );
stackobj.Push(23);                cout << stackobj.Pop( );
                                  }       55
stackobj.Push(46);                                   55
                                              10
stackobj.Push(37);
                                              37     10
stackobj.Push(10);                            46
               FIST, Multi Media University   23
Applications of Stack


We shall see two applications of the stack

1) Use of Stacks in Function Calls
2) Palindrome Checking



                FIST, Multi Media University
Use of Stacks in Function Calls
• Whenever a function begins execution an
  ACTIVATION RECORD (Stack Frame) is created
     • to store the current environment for that function which
       includes
This structure should LIFO                                Parameters
because , when a function
                                             Caller’s state information
terminates, the function with
which to resume execution is                            Local variables
the last function whose
activation record was saved.                        Temporary storage
                         FIST, Multi Media University
Stack
Activation Record
    Function4

    Function3                          Function3


    Function2                          Function2

    Function1                          Function1
            FIST, Multi Media University
Palindrome Checking

What is a palindrome?
 A palindrome is a word/sentence that is the
 same if read both ways.
 You might have noticed that if you push some
 characters into a stack and pop them out , they
 will appear in reverse order.
 So Stacks are used for this purpose.

                FIST, Multi Media University
Palindrome
• Here are some palindromes
MALAYALAM (a south Indian language)
RATS LIVE ON NO EVIL STAR
DAD
POP
RADAR
STEP ON NO PETS
MADAM             FIST, Multi Media University
implementation
#include <iostream.h>
#include <string.h>
class ADTstack
{ char stack[10];
   int topstack;
   public: ADTstack( ) {topstack = -1;};
         int empty() {if (topstack == -1) return 1; else return 0;};
         int full()  {if (topstack == 9) return 1; else return 0;};
         void push(char num)      {       if (!full()) { topstack++;
                                           stack[topstack] = num;
                                     }
                                    else cout<<" Stack is Full"<<endl;
                              FIST, }
                                    Multi Media University
implementation
char pop( )
{ char num;
 if (!empty())
{
     num = stack[topstack];
     topstack--; return num;
}
 else {cout<<"Stack is Empty"<<endl;
       return '0';}
}
};

                       FIST, Multi Media University
implementation
void main()
{
ADTstack st;
char str[10];
int palin, l,i;
     cout<<"type in a string to check if it is a palindrome"<<endl;
     cin>>str;
          l=strlen(str);
if (l==1) {palin=1;} //all strings with 1 character are palindromes
else
{

                              FIST, Multi Media University
implementation
i=0;
        while(str[i]!='0') //push the string into stack
                 { st.push(str[i]);
                           i++;
                 }
i=0;
while(str[i]!='0') //pop the string and compare with original
{                  if (str[i]!=st.pop()) {palin=0;break;}
                   i++;
}
}                  if (palin==0) cout<<"Not Palindrome"<<endl;
                   else cout<<"Palindrome"<<endl;
                             FIST, Multi Media University
}
Queue
What is a Queue?

  1) It is a data structure for storing some values
  2) It is an ADT.
  3) Implemented using Arrays or Linked List




                       FIST, Multi Media University
Queue
How to Store and Retrieve from a Queue?
 1) A Data Structure in which all Additions to the list are
   made at one end, and all Deletions from the list are
   made at other end.
   2) First item added to a queue (ADD) is always the first
   that will be removed (REMOVE) from the queue.
  3) This property is called First In First Out also known as
FIFO
  4) It can be maintained with two pointers namely FRONT
(REMOVE) and REAR ( ADD).
                     FIST, Multi Media University
Queue

EG - Bank Counter




   Front                                        Rear
                FIST, Multi Media University
Operations
There are Four operations :
         1) Addend ( )
                   used to add the data at the Tail of the Queue.
                   Check whether the Queue is full or not
         2) Serve ( )
                   used to remove data at the top of the stack.
                   Check whether the Queue is empty or not
         3) Empty ( )
                   Checks whether Queue is empty, Tail = -1
         4) Full ( )
                   checks whether Queue is full, Tail = maxqueuesize

                        FIST, Multi Media University
implementation
Uses ARRAY to represent a Queue
  Class Queue
 { private :
     int Queueelement[4],Head ,Tail;
   public:                                      int Empty( );
     Queue( ) { Head =0 ; Tail = -1} int Full ( );
     void Addend(int);                          };
     int Serve( ); FIST, Multi Media University
implementation

How to check for full?
 Int Queue :: Full( )
 {
    if (Tail == 3) return 1;
    else return 0;
 }

               FIST, Multi Media University
implementation

How to check for Empty?
 Int Queue :: Empty( )
 {
    if (Tail == -1) return 1;
    else return 0;
 }

               FIST, Multi Media University
implementation
How to Add?
Void Queue :: Addend(int data2add)
{ if (!Full( ))
   { Tail++;
     Queueelement[Tail] = data2add;
   }
   else
           cout << “Queue is Full!!!”<<endl;
}                FIST, Multi Media University
implementation
How to Delete?
int Queue :: Serve( )
{int data2remove;
 if (!Empty( ))
      { data2remove = Queueelement[0];
          for ( i =0;i<Tail;i++)
             Queueelement[i] = Queueelement[i+1]
        Tail--; return data2remove; }
  else{ cout << “Queue is Empty!!!”<<endl;
                                       Methods
                 FIST, Multi Media University
implementation

Void main( )
{                            queueobj.Addend(55);
                             cout << queueobj.Serve();
Queue queueobj;
                             cout << queueobj.Serve();
queueobj.Addend(23);         }
queueobj.Addend(46);
queueobj.Addend(37);
queueobj.Addend(10);             23        46     37    10   55
                                             23
                  FIST, Multi Media University     46
Serving

  Three Methods of Serving
  1) increment head to 1
     runs out of storage

  2) when the first person has be served the remaining persons in the
     Queue shuffle forward one place.
     Can serve unlimited number of persons as long as the queue never
     exceeds the maximum size

  3) Use cyclic queues


One of the application of Queues is simulation
                     FIST, Multi Media University
Lecture 6



• Cyclic Queues




              FIST, Multi Media University
Cyclic Queues
 What is a Cyclic Queue?
       we need to imagine that the array allocated to the queue
       is not linear but cyclic, i.e. that it forms a circle.

 EG:
  So that if for instance 10 elements are allocated to the queue with
  the element positions running from 0 to 9 then when the tail gets
  to position 9 the next element to be added can go to position 0
  providing that position has already been “served” (vacant).

.Thus the two problems of the queues are solved .
                           FIST, Multi Media University
Cyclic Queue

Example: Queue implemented using an array of size 6 with 4 data items
                                             inserted in to the queue



       Head                        Tail



            0 1 2 3 4 5
The following actions will cause the “head” and “tail” to
move through the arrayMulti Media University
                   FIST, as listed below:
Cyclic Queue
Action   Head               Tail
          0                   3
Delete    1                   3
Insert    1                   4
Delete    2                   4 Head              Tail
Insert    2                   5
Insert    2                   0
Delete    3                   0
Delete    4                   0         0 1   2     3    4   5
           FIST, Multi Media University
Cyclic Queue
Action            Head                Tail
Insert             4                   1   Head     Tail
Delete             5                   1
Insert             5                   2
Delete             0                   2
                                     0 1 2 3 4 5
Note: A Cyclic queue will always be of fixed size (say n)
 and the size information must be available to update
 the pointers “head” and “tail”.
                     FIST, Multi Media University
Cyclic Queue
The wrapping around can be achieved by updating the
pointers as follows:

Delete: head = (head+1) % n

Insert: tail = (tail + 1) % n
i.e., Whenever a pointer is incremented, take modulo n.
The above operations is needed to check if the queue is
 empty or full.
                   FIST, Multi Media University
Cyclic Queue

 Consider when there is only one element in the queue
• In this case, both the pointers coincide (head == tail)
• The queue becomes empty when the element is deleted
            Head ,Tail                Tail       Head



     0   1     2    3 4 5                0    1 2 3 4 5
                                              Empty Queue
    Only one elementFIST, Multi Media University
                     Queue
Cyclic Queue

For an empty queue, we have the condition
       head = (tail + 1) % n
The above condition is also satisfied when the queue is full
We resolve the ambiguity between two cases
  if the condition head = (tail+1)% n is satisfied up on deleting an
  item from the queue, then queue is empty
  if the condition head = (tail + 1) % n is satisfied up on inserting an
  item in to the queue, then queue is full.

                           FIST, Multi Media University
implementation

How to Add?
void Addend(int x)
{
if (!Full())
{
  tail=(tail+1)%MAX;
  a[tail]=x;
  count++;
  cout<<x<<" added to the queue"<<endl;
}
else cout<<"Full Queue"<<endl;
}                 FIST, Multi Media University
implementation

How to Delete?
int Serve()
{ int x;
if (!Empty())
{
  x=a[head];
  head=(head+1)%MAX;
  count--;
  cout<<x<<" served from the queue"<<endl;
      return x;
}
else cout<<"Empty FIST, Multi Media University
                   Queue"<<endl;               }

More Related Content

What's hot

Session2
Session2Session2
Session2vattam
 
Stack and Queue (brief)
Stack and Queue (brief)Stack and Queue (brief)
Stack and Queue (brief)Sanjay Saha
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPyDevashish Kumar
 
QwalKeko, a History Querying Tool
QwalKeko, a History Querying ToolQwalKeko, a History Querying Tool
QwalKeko, a History Querying Toolstevensreinout
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
Macroprocessor
MacroprocessorMacroprocessor
Macroprocessorksanthosh
 
BOSC 2008 Biopython
BOSC 2008 BiopythonBOSC 2008 Biopython
BOSC 2008 Biopythontiago
 
Making Better news with Spark by Philip Wills
Making Better news with Spark by Philip WillsMaking Better news with Spark by Philip Wills
Making Better news with Spark by Philip WillsSpark Summit
 
機械学習によるデータ分析 実践編
機械学習によるデータ分析 実践編機械学習によるデータ分析 実践編
機械学習によるデータ分析 実践編Ryota Kamoshida
 
Refactoring Edit History of Source Code
Refactoring Edit History of Source CodeRefactoring Edit History of Source Code
Refactoring Edit History of Source CodeShinpei Hayashi
 

What's hot (20)

NUMPY
NUMPY NUMPY
NUMPY
 
Session2
Session2Session2
Session2
 
Plotting data with python and pylab
Plotting data with python and pylabPlotting data with python and pylab
Plotting data with python and pylab
 
Stack and Queue (brief)
Stack and Queue (brief)Stack and Queue (brief)
Stack and Queue (brief)
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
 
QwalKeko, a History Querying Tool
QwalKeko, a History Querying ToolQwalKeko, a History Querying Tool
QwalKeko, a History Querying Tool
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
NumPy
NumPyNumPy
NumPy
 
Macroprocessor
MacroprocessorMacroprocessor
Macroprocessor
 
stack & queue
stack & queuestack & queue
stack & queue
 
Introduction to numpy
Introduction to numpyIntroduction to numpy
Introduction to numpy
 
Exploitation
ExploitationExploitation
Exploitation
 
Stack Algorithm
Stack AlgorithmStack Algorithm
Stack Algorithm
 
Numpy
NumpyNumpy
Numpy
 
BOSC 2008 Biopython
BOSC 2008 BiopythonBOSC 2008 Biopython
BOSC 2008 Biopython
 
Making Better news with Spark by Philip Wills
Making Better news with Spark by Philip WillsMaking Better news with Spark by Philip Wills
Making Better news with Spark by Philip Wills
 
Packages and Datastructures - Python
Packages and Datastructures - PythonPackages and Datastructures - Python
Packages and Datastructures - Python
 
機械学習によるデータ分析 実践編
機械学習によるデータ分析 実践編機械学習によるデータ分析 実践編
機械学習によるデータ分析 実践編
 
Refactoring Edit History of Source Code
Refactoring Edit History of Source CodeRefactoring Edit History of Source Code
Refactoring Edit History of Source Code
 
Scipy, numpy and friends
Scipy, numpy and friendsScipy, numpy and friends
Scipy, numpy and friends
 

Similar to 901230 lecture5&6

Data structure week y 5
Data structure week y 5Data structure week y 5
Data structure week y 5karmuhtam
 
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 QueueBalwant Gorad
 
Stacks in algorithems & data structure
Stacks in algorithems & data structureStacks in algorithems & data structure
Stacks in algorithems & data structurefaran nawaz
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queueAmit Vats
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdfTobyWtf
 
Stack operation algorithms with example
Stack operation algorithms with exampleStack operation algorithms with example
Stack operation algorithms with exampleNamanKikani
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理maruyama097
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
10 Linked Lists Sacks and Queues
10 Linked Lists Sacks and Queues10 Linked Lists Sacks and Queues
10 Linked Lists Sacks and QueuesPraveen M Jigajinni
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queuePulkitmodi1998
 

Similar to 901230 lecture5&6 (20)

Stack
StackStack
Stack
 
Data structure week y 5
Data structure week y 5Data structure week y 5
Data structure week y 5
 
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
 
Stacks in algorithems & data structure
Stacks in algorithems & data structureStacks in algorithems & data structure
Stacks in algorithems & data structure
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Stack
StackStack
Stack
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Stack project
Stack projectStack project
Stack project
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
04 stacks
04 stacks04 stacks
04 stacks
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdf
 
Stack operation algorithms with example
Stack operation algorithms with exampleStack operation algorithms with example
Stack operation algorithms with example
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
10 Linked Lists Sacks and Queues
10 Linked Lists Sacks and Queues10 Linked Lists Sacks and Queues
10 Linked Lists Sacks and Queues
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 

Recently uploaded

How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptxmary850239
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRATanmoy Mishra
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxAditiChauhan701637
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.raviapr7
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICESayali Powar
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17Celine George
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 

Recently uploaded (20)

How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptx
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdfPersonal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptx
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICE
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 

901230 lecture5&6

  • 1. Lecture 5 • Stack (Array Implementation) • Queue (Array Implementation ) FIST, Multi Media University
  • 2. Stack What is a Stack? 1) It is a data structure for storing some values 2) It is an ADT. 3) Implemented using Arrays or Linked List 4) used in Operating System and in System Programming FIST, Multi Media University
  • 3. Stack How to Store and Retrieve from a Stack? 1) All Insertions ( Storing) and Deletions (Removing) of entries are made at one end called the TOP of Stack 2) Last item added to a stack (PUSH) is always the first that will be removed (POP) from the stack. 3) This property is called Last In First Out also known as LIFO 4) The operations are done with a single pointer to the top of list of elements. FIST, Multi Media University Operations...
  • 4. Stack E TOP F D EG - Plates G C Books B (LIFO) A FIST, Multi Media University
  • 5. Operations • There are Four operations : 1) Push ( ) used to add the data at the top of the stack. Check whether the stack is full or not 2) Pop ( ) used to remove data at the top of the stack. Check whether the stack is empty or not 3) Empty ( ) Checks whether stack is empty, TOP = -1 4) Full ( ) checks whether stackUniversity TOP = maxstacksize FIST, Multi Media is full,
  • 6. Stack - implementation • Uses ARRAY to represent a stack Class stack { private : int stackelement[10],TOP; public: stack( ) { top = -1} int Empty( ); void push(int); int Full ( ); int Pop( ); Multi Media University }; FIST,
  • 7. Stack How to Push? Void stack :: Push(int data2add) { if (!Full( )) { TOP++; Stackelement[TOP] = data2add; } else cout << “Stack is Full!!!”<<endl; } FIST, Multi Media University
  • 8. Stack How to Pop? Int stack :: Pop( ) {int data2remove; if (!Empty( )) { data2remove = Stackelement[TOP]; TOP--; return data2remove; } else{ cout << “Stack is Empty!!!”<<endl; return 0; } } FIST, Multi Media University
  • 9. Stack How to check for full? Int Stack :: Full( ) { if (TOP==9) return 1; else return 0; } FIST, Multi Media University
  • 10. Stack How to check for Empty? Int Stack :: Empty( ) { if (TOP== -1) return 1; else return 0; } FIST, Multi Media University
  • 11. Stack Void main( ) { stackobj.Push(55); stack stackobj; cout << stackobj.Pop( ); stackobj.Push(23); cout << stackobj.Pop( ); } 55 stackobj.Push(46); 55 10 stackobj.Push(37); 37 10 stackobj.Push(10); 46 FIST, Multi Media University 23
  • 12. Applications of Stack We shall see two applications of the stack 1) Use of Stacks in Function Calls 2) Palindrome Checking FIST, Multi Media University
  • 13. Use of Stacks in Function Calls • Whenever a function begins execution an ACTIVATION RECORD (Stack Frame) is created • to store the current environment for that function which includes This structure should LIFO Parameters because , when a function Caller’s state information terminates, the function with which to resume execution is Local variables the last function whose activation record was saved. Temporary storage FIST, Multi Media University
  • 14. Stack Activation Record Function4 Function3 Function3 Function2 Function2 Function1 Function1 FIST, Multi Media University
  • 15. Palindrome Checking What is a palindrome? A palindrome is a word/sentence that is the same if read both ways. You might have noticed that if you push some characters into a stack and pop them out , they will appear in reverse order. So Stacks are used for this purpose. FIST, Multi Media University
  • 16. Palindrome • Here are some palindromes MALAYALAM (a south Indian language) RATS LIVE ON NO EVIL STAR DAD POP RADAR STEP ON NO PETS MADAM FIST, Multi Media University
  • 17. implementation #include <iostream.h> #include <string.h> class ADTstack { char stack[10]; int topstack; public: ADTstack( ) {topstack = -1;}; int empty() {if (topstack == -1) return 1; else return 0;}; int full() {if (topstack == 9) return 1; else return 0;}; void push(char num) { if (!full()) { topstack++; stack[topstack] = num; } else cout<<" Stack is Full"<<endl; FIST, } Multi Media University
  • 18. implementation char pop( ) { char num; if (!empty()) { num = stack[topstack]; topstack--; return num; } else {cout<<"Stack is Empty"<<endl; return '0';} } }; FIST, Multi Media University
  • 19. implementation void main() { ADTstack st; char str[10]; int palin, l,i; cout<<"type in a string to check if it is a palindrome"<<endl; cin>>str; l=strlen(str); if (l==1) {palin=1;} //all strings with 1 character are palindromes else { FIST, Multi Media University
  • 20. implementation i=0; while(str[i]!='0') //push the string into stack { st.push(str[i]); i++; } i=0; while(str[i]!='0') //pop the string and compare with original { if (str[i]!=st.pop()) {palin=0;break;} i++; } } if (palin==0) cout<<"Not Palindrome"<<endl; else cout<<"Palindrome"<<endl; FIST, Multi Media University }
  • 21. Queue What is a Queue? 1) It is a data structure for storing some values 2) It is an ADT. 3) Implemented using Arrays or Linked List FIST, Multi Media University
  • 22. Queue How to Store and Retrieve from a Queue? 1) A Data Structure in which all Additions to the list are made at one end, and all Deletions from the list are made at other end. 2) First item added to a queue (ADD) is always the first that will be removed (REMOVE) from the queue. 3) This property is called First In First Out also known as FIFO 4) It can be maintained with two pointers namely FRONT (REMOVE) and REAR ( ADD). FIST, Multi Media University
  • 23. Queue EG - Bank Counter Front Rear FIST, Multi Media University
  • 24. Operations There are Four operations : 1) Addend ( ) used to add the data at the Tail of the Queue. Check whether the Queue is full or not 2) Serve ( ) used to remove data at the top of the stack. Check whether the Queue is empty or not 3) Empty ( ) Checks whether Queue is empty, Tail = -1 4) Full ( ) checks whether Queue is full, Tail = maxqueuesize FIST, Multi Media University
  • 25. implementation Uses ARRAY to represent a Queue Class Queue { private : int Queueelement[4],Head ,Tail; public: int Empty( ); Queue( ) { Head =0 ; Tail = -1} int Full ( ); void Addend(int); }; int Serve( ); FIST, Multi Media University
  • 26. implementation How to check for full? Int Queue :: Full( ) { if (Tail == 3) return 1; else return 0; } FIST, Multi Media University
  • 27. implementation How to check for Empty? Int Queue :: Empty( ) { if (Tail == -1) return 1; else return 0; } FIST, Multi Media University
  • 28. implementation How to Add? Void Queue :: Addend(int data2add) { if (!Full( )) { Tail++; Queueelement[Tail] = data2add; } else cout << “Queue is Full!!!”<<endl; } FIST, Multi Media University
  • 29. implementation How to Delete? int Queue :: Serve( ) {int data2remove; if (!Empty( )) { data2remove = Queueelement[0]; for ( i =0;i<Tail;i++) Queueelement[i] = Queueelement[i+1] Tail--; return data2remove; } else{ cout << “Queue is Empty!!!”<<endl; Methods FIST, Multi Media University
  • 30. implementation Void main( ) { queueobj.Addend(55); cout << queueobj.Serve(); Queue queueobj; cout << queueobj.Serve(); queueobj.Addend(23); } queueobj.Addend(46); queueobj.Addend(37); queueobj.Addend(10); 23 46 37 10 55 23 FIST, Multi Media University 46
  • 31. Serving Three Methods of Serving 1) increment head to 1 runs out of storage 2) when the first person has be served the remaining persons in the Queue shuffle forward one place. Can serve unlimited number of persons as long as the queue never exceeds the maximum size 3) Use cyclic queues One of the application of Queues is simulation FIST, Multi Media University
  • 32. Lecture 6 • Cyclic Queues FIST, Multi Media University
  • 33. Cyclic Queues What is a Cyclic Queue? we need to imagine that the array allocated to the queue is not linear but cyclic, i.e. that it forms a circle. EG: So that if for instance 10 elements are allocated to the queue with the element positions running from 0 to 9 then when the tail gets to position 9 the next element to be added can go to position 0 providing that position has already been “served” (vacant). .Thus the two problems of the queues are solved . FIST, Multi Media University
  • 34. Cyclic Queue Example: Queue implemented using an array of size 6 with 4 data items inserted in to the queue Head Tail 0 1 2 3 4 5 The following actions will cause the “head” and “tail” to move through the arrayMulti Media University FIST, as listed below:
  • 35. Cyclic Queue Action Head Tail 0 3 Delete 1 3 Insert 1 4 Delete 2 4 Head Tail Insert 2 5 Insert 2 0 Delete 3 0 Delete 4 0 0 1 2 3 4 5 FIST, Multi Media University
  • 36. Cyclic Queue Action Head Tail Insert 4 1 Head Tail Delete 5 1 Insert 5 2 Delete 0 2 0 1 2 3 4 5 Note: A Cyclic queue will always be of fixed size (say n) and the size information must be available to update the pointers “head” and “tail”. FIST, Multi Media University
  • 37. Cyclic Queue The wrapping around can be achieved by updating the pointers as follows: Delete: head = (head+1) % n Insert: tail = (tail + 1) % n i.e., Whenever a pointer is incremented, take modulo n. The above operations is needed to check if the queue is empty or full. FIST, Multi Media University
  • 38. Cyclic Queue Consider when there is only one element in the queue • In this case, both the pointers coincide (head == tail) • The queue becomes empty when the element is deleted Head ,Tail Tail Head 0 1 2 3 4 5 0 1 2 3 4 5 Empty Queue Only one elementFIST, Multi Media University Queue
  • 39. Cyclic Queue For an empty queue, we have the condition head = (tail + 1) % n The above condition is also satisfied when the queue is full We resolve the ambiguity between two cases if the condition head = (tail+1)% n is satisfied up on deleting an item from the queue, then queue is empty if the condition head = (tail + 1) % n is satisfied up on inserting an item in to the queue, then queue is full. FIST, Multi Media University
  • 40. implementation How to Add? void Addend(int x) { if (!Full()) { tail=(tail+1)%MAX; a[tail]=x; count++; cout<<x<<" added to the queue"<<endl; } else cout<<"Full Queue"<<endl; } FIST, Multi Media University
  • 41. implementation How to Delete? int Serve() { int x; if (!Empty()) { x=a[head]; head=(head+1)%MAX; count--; cout<<x<<" served from the queue"<<endl; return x; } else cout<<"Empty FIST, Multi Media University Queue"<<endl; }