SlideShare uma empresa Scribd logo
1 de 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--;
 }

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
stack presentation
stack presentationstack presentation
stack presentation
 
Python Data Structures and Algorithms.pptx
Python Data Structures and Algorithms.pptxPython Data Structures and Algorithms.pptx
Python Data Structures and Algorithms.pptx
 
Stack and Queue
Stack and QueueStack and Queue
Stack and Queue
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Stack
StackStack
Stack
 
Stacks
StacksStacks
Stacks
 
Language design and translation issues
Language design and translation issuesLanguage design and translation issues
Language design and translation issues
 
Data structures
Data structuresData structures
Data structures
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Introduction to data structure
Introduction to data structure Introduction to data structure
Introduction to data structure
 
C Programming: Structure and Union
C Programming: Structure and UnionC Programming: Structure and Union
C Programming: Structure and Union
 
Linked list
Linked listLinked list
Linked list
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 

Destaque (20)

stack & queue
stack & queuestack & queue
stack & queue
 
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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
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
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
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
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 

Último (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
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...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.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
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
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
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

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--; }