SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Stack and Queue
Stack
A data structure where insertion can only
 be done in the end part and deletion can
 only be done in the end part as well
Last-in first-out data structure (LIFO)
Supports the following operations
  push – inserts an item at the end
  pop – deletes the end item
  peek – returns the last element
Stack
 Study the code below

  Stack s;

  for(int i=10; i<25; i+=3)
   s.push(i);

  s.display();
  s.pop();
  s.display();
  s.push(100);
  s.display();
  cout<<s.peek()<<endl;
Array Implementation of Stack
 Just like the array implementation of the List, we
  also need the array of items where we are going
  to store the elements of the Stack
 Aside from this, we also need an object that
  keeps track of where the last element is located
   From this point on, we are going to call it the top
   top is simply an integer (very much like the head in
    the cursor implementation of the List)
Array Implementation of Stack
 Our Stack class should look very much like this:
   const MAX = 100;
   class Stack{
   private:
      int top, items[MAX];
   public:
      Stack();
      bool push(int);
      bool pop();
      int peek(); //int top();
      bool isEmpty();
      bool isFull();
      void display();
   };
Array Implementation of Stack
 The constructor             The push
    Stack::Stack(){             bool Stack::push(int x){
       top = -1;                   if(isFull())
    }
                                      return false;
 The full check
                                   items[++top] = x;
    bool Stack::isFull(){
       if(top+1==MAX)              return true;
          return true;          }
       return false;          The pop
    }                           bool Stack::pop(){
 The empty check                  if(isEmpty())
    bool Stack::isEmpty(){
                                      return false;
       if(top==-1)
          return true;             top--;
       return false;               return true;
    }                           }
Array Implementation of Stack
top = -1



  10        13      16      19      22


top=0      top=1   top=2   top=3   top=4
Array Implementation of Stack


 10      13      43
                 16      19
                         107     22


top=0   top=1   top=2   top=3   top=4
Array Implementation of Stack
 The peek
  int Stack::peek(){
     return items[top];
  }
 The display
  void Stack::display(){
    for(int i=top; i>=0; i--)
      cout<<items[i]<<endl;
  }
Linked-list Implementation of Stack
This implementation is the linked-list
 implementation of the list except for the
 following operations
  General insert and append
  General delete
Linked-list Implementation of Stack

    head:                 tail:
    44      97       23   17


                 9
Linked-list Implementation of Stack
PUSH
                            top:
    44     97          23   17


                9

                top:
Linked-list Implementation of Stack
 POP
       head:                      top:
       44      97          23     17
       tmp     tmp         tmp    tmp

                     9     top:
                     del
Linked-list Implementation of Stack
 The class Stack can be declared as below
   class Stack{
   private:
      node *head, *top;
   public:
      Stack();
      bool push(int);
      bool pop();
      int peek(); //int top();
      bool isEmpty();
      void display();
      ~Stack();
   };
Linked-list Implementation of Stack
 The constructor
  Stack::Stack(){
    head = top = NULL;
  }
 The empty check
  bool Stack::isEmpty(){
    if(top==NULL)
      return true;
    return false;
  }
Linked-list Implementation of Stack
 The push
  bool Stack::push(int x){
    node *n = new node(x);

      if(n==NULL)
         return false;
      if(isEmpty())
         head = top = n;
      else{
         top->next = n;
         top = n;
      }
      return true;
  }
Linked-list Implementation of Stack
 The pop
   bool Stack::pop(){
       if(isEmpty())
           return false;
       node *tmp = head;
       node *del;
       if(tmp == top){
           del = top;
           delete del;
           head = top = NULL;
       }
       else{
           while(tmp->next!=top)
                         tmp = tmp->next;
           del = tmp->next;
           tmp->next = NULL;
           top = tmp;
           delete del;
       }
       return true;
   }
Doubly-linked List Implementation
             of Stack
 Let us review the pop of the singly-linked list
  implementation of Stack
 Let’s us change the definition of a node
 Why not include a pointer to the previous node as well?
   class node{
   public:
      int item;
      node *next, *prev;
      node(int);
      node();
   };
Doubly-linked List Implementation
            of Stack

                           top

   23          5           90




               49   top
Doubly-linked List Implementation
            of Stack

                         top

  23          5          90




        del   49   top
Doubly-linked List Implementation
             of Stack
 The push
  bool Stack::push(int x){
    node *n = new node(x);

      if(n==NULL)
         return false;
      if(isEmpty())
         top = n;
      else{
         top->next = n;
         n->prev = top;
         top = n;
      }
      return true;
  }
Doubly-linked List Implementation
            of Stack
The pop
 bool Stack::pop(){
   if(isEmpty())
      return false;
   node *del = top;
   top = top->prev;
   if(top!=NULL)
      top->next = NULL;
   del->prev = NULL;
   return true;
 }
Queue
 The Queue is like the List but with “limited”
  insertion and deletion.
 Insertion can be done only at the end or rear
 Deletion can only be done in the front
 FIFO – first-in-first-out data structure
 Operations
   enqueue
   dequeue
Queue
Queue<int> q;
try{
        cout<<q.front()<<endl;
}
catch(char *msg){
        cout<<msg<<endl;
}
for(int i=10; i<25; i+=3)
        q.enqueue(i);
q.display();
q.dequeue();
q.display();
q.enqueue(100);
q.display();
 cout<<"front: "<<q.front()<<" rear: "<<q.rear()<<endl;
Array Implementation of Queue
 Just like the array implementation of the List, we
  also need the array of items where we are going
  to store the elements of the Queue
 Aside from this, we also need an object that
  keeps track of where the first and last elements
  are located
   Size will do
Array Implementation of Queue
 Our Queue class should look very much like this:
   const MAX = 100;
   template <class type>
   class Queue{
   private:
      int size, items[MAX];
   public:
      Queue();
      bool enqueue(type);
      bool dequeue();
      type front();
      type rear();
      bool isEmpty();
      bool isFull();
      void display();
   };
Array Implementation of Queue
                               The enqueue
 The constructor                bool Queue :: enqueue(type x){
    Queue:: Queue(){                if(isFull())
      size= 0;                         return false;
    }
                                    items[size++] = x;
 The full check
    bool Queue ::isFull(){          return true;
       if(size==MAX)             }
          return true;         The dequeue
       return false;             bool Queue :: dequeue(){
    }                               if(isEmpty())
 The empty check
                                       return false;
    bool Queue ::isEmpty(){
       if(size==0)                  for(int i=1; i<size; i++)
          return true;                 items[i-1] = items[i];
       return false;                size--;
    }                               return true;
                                 }
Array Implementation of Queue
size= 0



 10       13   16     19     22


size=1 size=2 size=3 size=4 size=5
Array Implementation of Queue


   10   13    16   19     22


size=1 size=2 size=3 size=4 size=5
Array Implementation of Queue


   13    16   19    22    22


size=1 size=2 size=3 size=4
Circular Array Implementation
Dequeue takes O(n) time.
This can be improved by simulating a
 circular array.
Circular Array

front
 rear   front   front                        rear rear   rear


 -4
 10     13      16      19     22   2   15   7     5     34
Array Implementation of Queue
 Our Queue class should look very much like this:
   const MAX = 100;
   template <class type>
   class Queue{
   private:
      int front, rear, items[MAX];
   public:
      Queue();
      bool enqueue(type);
      bool dequeue();
      type front();
      type rear();
      bool isEmpty();
      bool isFull();
      void display();
   };
Array Implementation of Queue
                               The enqueue
 The constructor                bool Queue :: enqueue(type x){
    Queue:: Queue(){
      front=rear=-1;                if(isFull())
      size=0;                          return false;
    }                               if(isEmpty()){
 The full check                       front = rear = 0;
    bool Queue ::isFull(){             items[rear] = x;
       if(size==MAX)
                                    }
          return true;
       return false;                else{
    }                                  rear = (rear + 1)%MAX;
 The empty check                      items[rear] = x;
    bool Queue ::isEmpty(){         }
       if(size==0)                  size++;
          return true;
                                    return true;
       return false;
    }                            }
Circular Array Implementation
The dequeue
 bool Queue :: dequeue(){
    if(isEmpty())
       return false;
    front=(front+1)%MAX;
    size--;
 }

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Linked list
Linked listLinked list
Linked list
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Stack
StackStack
Stack
 
stack and queue array implementation in java.
stack and queue array implementation in java.stack and queue array implementation in java.
stack and queue array implementation in java.
 
Stacks
StacksStacks
Stacks
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Queues
QueuesQueues
Queues
 
Stack
StackStack
Stack
 
Stack
StackStack
Stack
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
Expression evaluation
Expression evaluationExpression evaluation
Expression evaluation
 
Data structures
Data structuresData structures
Data structures
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
Queue as data_structure
Queue as data_structureQueue as data_structure
Queue as data_structure
 

Andere mochten auch (20)

Stack & queue
Stack & queueStack & queue
Stack & queue
 
Stack and Queue (brief)
Stack and Queue (brief)Stack and Queue (brief)
Stack and Queue (brief)
 
single linked list
single linked listsingle linked list
single linked list
 
comp.org Chapter 2
comp.org Chapter 2comp.org Chapter 2
comp.org Chapter 2
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
group 7
group 7group 7
group 7
 
Data structures
Data structuresData structures
Data structures
 
Computer Organization and Assembly Language
Computer Organization and Assembly LanguageComputer Organization and Assembly Language
Computer Organization and Assembly Language
 
Computer organization and architecture
Computer organization and architectureComputer organization and architecture
Computer organization and architecture
 
Input Output Operations
Input Output OperationsInput Output Operations
Input Output Operations
 
Queue and stacks
Queue and stacksQueue and stacks
Queue and stacks
 
Ebw
EbwEbw
Ebw
 
Computer architecture
Computer architectureComputer architecture
Computer architecture
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
ELECTRON BEAM WELDING (EBW) PPT
ELECTRON BEAM WELDING (EBW) PPTELECTRON BEAM WELDING (EBW) PPT
ELECTRON BEAM WELDING (EBW) PPT
 
Computer Architecture – An Introduction
Computer Architecture – An IntroductionComputer Architecture – An Introduction
Computer Architecture – An Introduction
 
Input Output Organization
Input Output OrganizationInput Output Organization
Input Output Organization
 
Computer architecture and organization
Computer architecture and organizationComputer architecture and organization
Computer architecture and organization
 
Linked lists
Linked listsLinked lists
Linked lists
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
 

Ähnlich wie Stack and queue

03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfarorastores
 
Link list part 2
Link list part 2Link list part 2
Link list part 2Anaya Zafar
 
Datastructures asignment
Datastructures asignmentDatastructures asignment
Datastructures asignmentsreekanth3dce
 
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
 
C program for array implementation of stack#include stdio.h.pdf
 C program for array implementation of stack#include stdio.h.pdf C program for array implementation of stack#include stdio.h.pdf
C program for array implementation of stack#include stdio.h.pdfmohammadirfan136964
 
please tell me what lines do i alter to make this stack a queue. tel.pdf
please tell me what lines do i alter to make this stack a queue. tel.pdfplease tell me what lines do i alter to make this stack a queue. tel.pdf
please tell me what lines do i alter to make this stack a queue. tel.pdfagarshailenterprises
 

Ähnlich wie Stack and queue (20)

03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
 
Lect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.pptLect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.ppt
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stacks
StacksStacks
Stacks
 
Stack
StackStack
Stack
 
Link list part 2
Link list part 2Link list part 2
Link list part 2
 
Datastructures asignment
Datastructures asignmentDatastructures asignment
Datastructures asignment
 
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
 
C program for array implementation of stack#include stdio.h.pdf
 C program for array implementation of stack#include stdio.h.pdf C program for array implementation of stack#include stdio.h.pdf
C program for array implementation of stack#include stdio.h.pdf
 
please tell me what lines do i alter to make this stack a queue. tel.pdf
please tell me what lines do i alter to make this stack a queue. tel.pdfplease tell me what lines do i alter to make this stack a queue. tel.pdf
please tell me what lines do i alter to make this stack a queue. tel.pdf
 

Mehr von Katang Isip

Reflection paper
Reflection paperReflection paper
Reflection paperKatang Isip
 
Punctuation tips
Punctuation tipsPunctuation tips
Punctuation tipsKatang Isip
 
Class list data structure
Class list data structureClass list data structure
Class list data structureKatang Isip
 
Hash table and heaps
Hash table and heapsHash table and heaps
Hash table and heapsKatang Isip
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVLKatang Isip
 

Mehr von Katang Isip (7)

Reflection paper
Reflection paperReflection paper
Reflection paper
 
Punctuation tips
Punctuation tipsPunctuation tips
Punctuation tips
 
3 act story
3 act story3 act story
3 act story
 
Class list data structure
Class list data structureClass list data structure
Class list data structure
 
Hash table and heaps
Hash table and heapsHash table and heaps
Hash table and heaps
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Time complexity
Time complexityTime complexity
Time complexity
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 

Kürzlich hochgeladen (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 

Stack and queue

  • 2. Stack A data structure where insertion can only be done in the end part and deletion can only be done in the end part as well Last-in first-out data structure (LIFO) Supports the following operations push – inserts an item at the end pop – deletes the end item peek – returns the last element
  • 3. Stack  Study the code below Stack s; for(int i=10; i<25; i+=3) s.push(i); s.display(); s.pop(); s.display(); s.push(100); s.display(); cout<<s.peek()<<endl;
  • 4. Array Implementation of Stack  Just like the array implementation of the List, we also need the array of items where we are going to store the elements of the Stack  Aside from this, we also need an object that keeps track of where the last element is located  From this point on, we are going to call it the top  top is simply an integer (very much like the head in the cursor implementation of the List)
  • 5. Array Implementation of Stack  Our Stack class should look very much like this: const MAX = 100; class Stack{ private: int top, items[MAX]; public: Stack(); bool push(int); bool pop(); int peek(); //int top(); bool isEmpty(); bool isFull(); void display(); };
  • 6. Array Implementation of Stack  The constructor  The push Stack::Stack(){ bool Stack::push(int x){ top = -1; if(isFull()) } return false;  The full check items[++top] = x; bool Stack::isFull(){ if(top+1==MAX) return true; return true; } return false;  The pop } bool Stack::pop(){  The empty check if(isEmpty()) bool Stack::isEmpty(){ return false; if(top==-1) return true; top--; return false; return true; } }
  • 7. Array Implementation of Stack top = -1 10 13 16 19 22 top=0 top=1 top=2 top=3 top=4
  • 8. Array Implementation of Stack 10 13 43 16 19 107 22 top=0 top=1 top=2 top=3 top=4
  • 9. Array Implementation of Stack  The peek int Stack::peek(){ return items[top]; }  The display void Stack::display(){ for(int i=top; i>=0; i--) cout<<items[i]<<endl; }
  • 10.
  • 11. Linked-list Implementation of Stack This implementation is the linked-list implementation of the list except for the following operations General insert and append General delete
  • 12. Linked-list Implementation of Stack head: tail: 44 97 23 17 9
  • 13. Linked-list Implementation of Stack PUSH top: 44 97 23 17 9 top:
  • 14. Linked-list Implementation of Stack POP head: top: 44 97 23 17 tmp tmp tmp tmp 9 top: del
  • 15. Linked-list Implementation of Stack  The class Stack can be declared as below class Stack{ private: node *head, *top; public: Stack(); bool push(int); bool pop(); int peek(); //int top(); bool isEmpty(); void display(); ~Stack(); };
  • 16. Linked-list Implementation of Stack  The constructor Stack::Stack(){ head = top = NULL; }  The empty check bool Stack::isEmpty(){ if(top==NULL) return true; return false; }
  • 17. Linked-list Implementation of Stack  The push bool Stack::push(int x){ node *n = new node(x); if(n==NULL) return false; if(isEmpty()) head = top = n; else{ top->next = n; top = n; } return true; }
  • 18. Linked-list Implementation of Stack  The pop bool Stack::pop(){ if(isEmpty()) return false; node *tmp = head; node *del; if(tmp == top){ del = top; delete del; head = top = NULL; } else{ while(tmp->next!=top) tmp = tmp->next; del = tmp->next; tmp->next = NULL; top = tmp; delete del; } return true; }
  • 19. Doubly-linked List Implementation of Stack  Let us review the pop of the singly-linked list implementation of Stack  Let’s us change the definition of a node  Why not include a pointer to the previous node as well? class node{ public: int item; node *next, *prev; node(int); node(); };
  • 20. Doubly-linked List Implementation of Stack top 23 5 90 49 top
  • 21. Doubly-linked List Implementation of Stack top 23 5 90 del 49 top
  • 22. Doubly-linked List Implementation of Stack  The push bool Stack::push(int x){ node *n = new node(x); if(n==NULL) return false; if(isEmpty()) top = n; else{ top->next = n; n->prev = top; top = n; } return true; }
  • 23. Doubly-linked List Implementation of Stack The pop bool Stack::pop(){ if(isEmpty()) return false; node *del = top; top = top->prev; if(top!=NULL) top->next = NULL; del->prev = NULL; return true; }
  • 24. Queue  The Queue is like the List but with “limited” insertion and deletion.  Insertion can be done only at the end or rear  Deletion can only be done in the front  FIFO – first-in-first-out data structure  Operations  enqueue  dequeue
  • 25. Queue Queue<int> q; try{ cout<<q.front()<<endl; } catch(char *msg){ cout<<msg<<endl; } for(int i=10; i<25; i+=3) q.enqueue(i); q.display(); q.dequeue(); q.display(); q.enqueue(100); q.display(); cout<<"front: "<<q.front()<<" rear: "<<q.rear()<<endl;
  • 26. Array Implementation of Queue  Just like the array implementation of the List, we also need the array of items where we are going to store the elements of the Queue  Aside from this, we also need an object that keeps track of where the first and last elements are located  Size will do
  • 27. Array Implementation of Queue  Our Queue class should look very much like this: const MAX = 100; template <class type> class Queue{ private: int size, items[MAX]; public: Queue(); bool enqueue(type); bool dequeue(); type front(); type rear(); bool isEmpty(); bool isFull(); void display(); };
  • 28. Array Implementation of Queue  The enqueue  The constructor bool Queue :: enqueue(type x){ Queue:: Queue(){ if(isFull()) size= 0; return false; } items[size++] = x;  The full check bool Queue ::isFull(){ return true; if(size==MAX) } return true;  The dequeue return false; bool Queue :: dequeue(){ } if(isEmpty())  The empty check return false; bool Queue ::isEmpty(){ if(size==0) for(int i=1; i<size; i++) return true; items[i-1] = items[i]; return false; size--; } return true; }
  • 29. Array Implementation of Queue size= 0 10 13 16 19 22 size=1 size=2 size=3 size=4 size=5
  • 30. Array Implementation of Queue 10 13 16 19 22 size=1 size=2 size=3 size=4 size=5
  • 31. Array Implementation of Queue 13 16 19 22 22 size=1 size=2 size=3 size=4
  • 32. Circular Array Implementation Dequeue takes O(n) time. This can be improved by simulating a circular array.
  • 33. Circular Array front rear front front rear rear rear -4 10 13 16 19 22 2 15 7 5 34
  • 34. Array Implementation of Queue  Our Queue class should look very much like this: const MAX = 100; template <class type> class Queue{ private: int front, rear, items[MAX]; public: Queue(); bool enqueue(type); bool dequeue(); type front(); type rear(); bool isEmpty(); bool isFull(); void display(); };
  • 35. Array Implementation of Queue  The enqueue  The constructor bool Queue :: enqueue(type x){ Queue:: Queue(){ front=rear=-1; if(isFull()) size=0; return false; } if(isEmpty()){  The full check front = rear = 0; bool Queue ::isFull(){ items[rear] = x; if(size==MAX) } return true; return false; else{ } rear = (rear + 1)%MAX;  The empty check items[rear] = x; bool Queue ::isEmpty(){ } if(size==0) size++; return true; return true; return false; } }
  • 36. Circular Array Implementation The dequeue bool Queue :: dequeue(){ if(isEmpty()) return false; front=(front+1)%MAX; size--; }