SlideShare a Scribd company logo
Stacks
What is a stack?
    Stores a set of elements in a particular order
    Stack principle: LAST IN FIRST OUT
    = LIFO
    It means: the last element inserted is the first one to
     be removed
    Example
    Which is the first element to pick up?
Last In First Out




                                                top
                                      top   E
                                  D         D         D
                        C   top   C         C         C
              B   top   B         B         B         B
              A         A         A         A         A
    A   top
Stack Applications
    Real life
        Pile of books, files, plates
        TOH
    More applications related to computer science
        stack Program execution
        Evaluating expressions
        Palindrome finder
        Parentheses matcher
    A Palindrome is a string that reads the same in
     either direction
        Examples: “Able was I ere I saw Elba”
Stack
objects: a finite ordered list with zero or more elements.
methods:

 Stack createS(max_stack_size) ::=
         create an empty stack whose maximum size is
         max_stack_size
 Boolean isFull(stack, max_stack_size) ::=
         if (number of elements in stack == max_stack_size)
          return TRUE
         else return FALSE
 Stack push(stack, item) ::=
         if (IsFull(stack)) stack_full
         else insert item into top of stack and return
Stack (cont’d)


Boolean isEmpty(stack) ::=
                   if(stack == CreateS(max_stack_size))
                  return TRUE
                  else return FALSE
Element pop(stack) ::=
                   if(IsEmpty(stack)) return
                  else remove and return the item on the
top of the stack.
Array-based Stack Implementation
   Allocate an array of some size (pre-defined)
       Maximum N elements in stack
   Bottom stack element stored at element 0
   last index in the array is the top
   Increment top when one element is pushed,
    decrement after pop
Stack Implementation
       #include <stdio.h>
       #include<conio.h>
       # define MAXSIZE 200

       int stack[MAXSIZE];
       int top; //index pointing to the top of stack
       void main()
       {
       void push(int);
       int pop();
       int will=1,i,num;
       clrscr();

       while(will ==1)
       {
       printf(" MAIN MENU:n 1.Add element to stackn2.Delete element from the stack");
       scanf("%d",&will);



    8                                                   Chapter 5: Stacks
   switch(will)
   {
   case 1:
         printf("Enter the data... ");
         scanf("%d",&num);
         push(num);
         break;
   case 2: i=pop();
         printf("Value returned from pop function is %d ",i);
         break;
   default: printf("Invalid Choice . ");
   }

   printf(" Do you want to do more operations on Stack ( 1 for yes, any
    other key to exit) ");
   scanf("%d" , &will);
   } //end of outer while
   }          //end of main

    9                                      Chapter 5: Stacks
    void push(int y)
    {

    if(top>MAXSIZE)
         {
         printf("nSTACK FULL");
         return;
         }
    else
           {
           top++;
           stack[top]=y;
           }
    }
    10                              Chapter 5: Stacks
    int pop()
    {
    int a;
    if(top<=0)
           {
           printf("STACK EMPTY ");
           return 0;
           }
    else
           {
           a=stack[top];
           top--;
           }
    return(a);

    }


    11                                Chapter 5: Stacks
The Towers of Hanoi
A Stack-based Application


     GIVEN: three poles
     a set of discs on the first pole, discs of different sizes, the
      smallest discs at the top
     GOAL: move all the discs from the left pole to the right one.
     CONDITIONS: only one disc may be moved at a time.
     A disc can be placed either on an empty pole or on top of a
      larger disc.
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Polish(prefix) notation
    - * / 15 - 7 + 1 1 3 + 2 + 1 1
     = - * / 15 - 7 2 3 + 2 + 1 1
     = - * / 15 5 3 + 2 + 1 1
     =-*33+2+11
    =-9+2+11
    =-9+22
    =-94
    =5


         An equivalent in-fix is as follows:
         ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5
    21                                                Chapter 5: Stacks
STACK OPERATIONS
REVERSE POLISH NOTATION (postfix)
   Reverse polish notation :is a postfix notation
    (places operators after operands)

   (Example)
     Infix notation      A+B
    Reverse Polish notation  AB+ also called
    postfix.
STACK OPERATIONS
REVERSE POLISH NOTATION (postfix)
   A stack organization is very effective for evaluating
    arithmetic expressions

   A*B+C*D           (AB *)+(CD *)     AB * CD * +

   (3*4)+(5*6)          34 * 56 * +
STACK OPERATIONS
REVERSE POLISH NOTATION (postfix)
n   • Evaluation procedure:

n   1. Scan the expression from left to right.
    2. When an operator is reached, perform the operation with the two
    operands found on the left side of the operator.
    3. Replace the two operands and the operator by the result obtained
    from the operation.

n   (Example)
     infix 3 * 4 + 5 * 6 = 42
     postfix 3 4 * 5 6 * +

n   12 5 6 * +
    12 30 +
    42
STACK OPERATIONS
REVERSE POLISH NOTATION (postfix)
   • Reverse Polish notation evaluation with a stack.
    Stack is the most efficient way for evaluating arithmetic
    expressions.




            stack evaluation:
           Get value
           If value is data: push data
           Else if value is operation: pop, pop
           evaluate and push.
STACK OPERATIONS
REVERSE POLISH NOTATION (postfix)

 (Example) using stacks to do
  this.
    3 * 4 + 5 * 6 = 42
=> 3 4 * 5 6 * +
Queue




27
The Queue Operations


    A queue is like a line
     of people waiting for a
     bank teller. The queue
     has a front and a
     rear.                             $ $




                               Front
              Rear
The Queue Operations


    New people must enter the queue at
     the rear. The C++ queue class calls
     this a push, although it is usually
     called an enqueue operation.
                                           $ $




                              Front
        Rear
The Queue Operations


    When an item is taken from the queue,
     it always comes from the front. The
     C++ queue calls this a pop, although it
     is usually called a dequeue operation.
                                               $ $




                                     Front
             Rear
The Queue Class

 The C++              template <class Item>
  standard             class queue<Item>
  template library     {
  has a queue          public:
  template class.           queue( );
                            void push(const Item&
 The template
                       entry);
  parameter is the          void pop( );
  type of the items         bool empty( ) const;
  that can be put in        Item front( ) const;
  the queue.                …
Array Implementation
    A queue can be implemented with an array, as
     shown here. For example, this queue contains
     the integers 4 (at the front), 8 and 6 (at the rear).


      [0]     [1]   [2]   [3]    [4]    [5]    ...

       4      8      6

An array of
integers to
implement a                   We don't care what's in
queue of integers              this part of the array.
Array Implementation


    The easiest implementation also                     3   size
     keeps track of the number of items in
     the queue and the index of the first                    first
                                                         0
     element (at the front of the queue),
     the last element (at the rear).
                                                         2   last


          [0]    [1]   [2]   [3]   [4]       [5]   ...

           4      8     6
A Dequeue Operation


    When an element leaves the queue,               2   size
     size is decremented, and first
     changes, too.                                       first
                                                     1


                                                     2   last


          [0]   [1]   [2]   [3]   [4]    [5]   ...

           4    8      6
An Enqueue Operation


    When an element enters the queue,               3   size
     size is incremented, and last
     changes, too.                                       first
                                                     1


                                                     3   last


          [0]   [1]   [2]   [3]   [4]    [5]   ...

                 8     6     2
At the End of the Array


    There is special behavior at the end       3   size
     of the array. For example, suppose
     we want to add a new element to this           first
                                                3
     queue, where the last index is [5]:

                                                5   last


          [0]    [1]   [2]   [3]   [4]   [5]
                              2     6       1
At the End of the Array

    The new element goes at the front of          4   size
     the array (if that spot isn’t already
     used):                                            first
                                                   3


                                                   0   last


          [0]    [1]   [2]   [3]   [4]       [5]
           4                  2      6       1
Array Implementation


    Easy to implement                                        3   size
    But it has a limited capacity with a fixed array
    Or you must use a dynamic array for an                   0   first
     unbounded capacity
    Special behavior is needed when the rear
                                                              2   last
     reaches the end of the array.

           [0]     [1]   [2]    [3]     [4]    [5]      ...

            4       8      6
Linked List Implementation


    A queue can also be
     implemented with a linked list
     with both a head and a tail        13
     pointer.
                                              15


                                        10

                                               7
                                              null
                        head_ptr
                                   tail_ptr
Linked List Implementation


    Which end do you think is the
     front of the queue? Why?
                                       13

                                             15


                                       10

                                              7
                                             null
                       head_ptr
                                  tail_ptr
Linked List Implementation


  The head_ptr points to the
   front of the list.
  Because it is harder to remove      Front
                                    13
   items from the tail of the list.
                                            15


                                      10

                                               7
                                            null
                      head_ptr
                                 tail_ptr
                                               Rear
A priority queue is a container in which
 access or deletion is of the highest-
 priority item, according to some way of
 Assigning priorities to items.




42                      Priority Queues
FOR EXAMPLE, SUPPOSE A HOSPITAL
EMERGENCY ROOM HAS THE
FOLLOWING FOUR PATIENTS, WITH
NAME, PRIORITY, AND INJURY:




43              Priority Queues
Matt 20 sprained ankle

Andrew 45 broken leg

Samira 20 high blood pressure

Kerem 83 heart attack


IN WHAT ORDER SHOULD THE
PATIENTS BE TREATED?
 44                    Priority Queues
THERE ARE MANY APPLICATIONS
OF PRIORITY QUEUES, IN AREAS AS
DIVERSE AS SCHEDULING, DATA
COMPRESSION, AND JPEG (Joint
Photographic Experts Group) ENCODING.




45                 Priority Queues
Using Priority Queue to
Track Your Assignments
   Organize class or work assignments by due dates
       Early due date, higher priority
       diagram of class Assignment

More Related Content

What's hot

Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
A-Tech and Software Development
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
Roman Rodomansky
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
Zidny Nafan
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
Mekk Mhmd
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Lovely Professional University
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
V.V.Vanniaperumal College for Women
 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
Rajendran
 
Queues
QueuesQueues
Queues
Hareem Aslam
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
Muhazzab Chouhadry
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
Vineeta Garg
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
Selvin Josy Bai Somu
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
Muhazzab Chouhadry
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
Trupti Agrawal
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
Dumindu Pahalawatta
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
SSE_AndyLi
 
Queue
QueueQueue
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queueSenthil Kumar
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
gomathi chlm
 

What's hot (20)

Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
stack & queue
stack & queuestack & queue
stack & queue
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Queues
QueuesQueues
Queues
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
 
Stack, queue and hashing
Stack, queue and hashingStack, queue and hashing
Stack, queue and hashing
 
5 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart25 chapter3 list_stackqueuepart2
5 chapter3 list_stackqueuepart2
 
Queue
QueueQueue
Queue
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
 

Viewers also liked

Data Manipulation
Data ManipulationData Manipulation
Data ManipulationAsfi Bhai
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of Example
Hitesh Kumar
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues iiTech_MX
 
Data manipulation instructions
Data manipulation instructionsData manipulation instructions
Data manipulation instructionsMahesh Kumar Attri
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
anooppjoseph
 

Viewers also liked (8)

Data Manipulation
Data ManipulationData Manipulation
Data Manipulation
 
Data structure by Digvijay
Data structure by DigvijayData structure by Digvijay
Data structure by Digvijay
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of Example
 
Applications of queues ii
Applications of queues   iiApplications of queues   ii
Applications of queues ii
 
Data manipulation instructions
Data manipulation instructionsData manipulation instructions
Data manipulation instructions
 
Data structures
Data structuresData structures
Data structures
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 

Similar to U3.stack queue

Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7Kumar
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
stack presentation
stack presentationstack presentation
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
Rai University
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Hariz Mustafa
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
RAtna29
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
Lect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.pptLect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.ppt
ThekkepatSankalp
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
AliRaza899305
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Stacks
StacksStacks
Stacks
sweta dargad
 
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.pptlecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
partho5958
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
Teksify
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
venaymagen19
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
MouDhara1
 

Similar to U3.stack queue (20)

Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
stack presentation
stack presentationstack presentation
stack presentation
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3Lecture08 stacks and-queues_v3
Lecture08 stacks and-queues_v3
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Lect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.pptLect-28-Stack-Queue.ppt
Lect-28-Stack-Queue.ppt
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Stacks
StacksStacks
Stacks
 
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.pptlecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
lecture10trsgfchjvxgfzfdchgdchgcgshyjh.ppt
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
 
Educational slides by venay magen
Educational slides by venay magenEducational slides by venay magen
Educational slides by venay magen
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 

More from Ssankett Negi

Threaded binarytree&heapsort
Threaded binarytree&heapsortThreaded binarytree&heapsort
Threaded binarytree&heapsortSsankett Negi
 
Stack prgs
Stack prgsStack prgs
Stack prgs
Ssankett Negi
 
Recursion
RecursionRecursion
Recursion
Ssankett Negi
 
Qprgs
QprgsQprgs
Circular queues
Circular queuesCircular queues
Circular queues
Ssankett Negi
 
U2.linked list
U2.linked listU2.linked list
U2.linked list
Ssankett Negi
 

More from Ssankett Negi (10)

Binary tree
Binary treeBinary tree
Binary tree
 
Multi way&btree
Multi way&btreeMulti way&btree
Multi way&btree
 
Heapsort
HeapsortHeapsort
Heapsort
 
Binary trees
Binary treesBinary trees
Binary trees
 
Threaded binarytree&heapsort
Threaded binarytree&heapsortThreaded binarytree&heapsort
Threaded binarytree&heapsort
 
Stack prgs
Stack prgsStack prgs
Stack prgs
 
Recursion
RecursionRecursion
Recursion
 
Qprgs
QprgsQprgs
Qprgs
 
Circular queues
Circular queuesCircular queues
Circular queues
 
U2.linked list
U2.linked listU2.linked list
U2.linked list
 

Recently uploaded

Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WAPaddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
River Recreation - Washington Whitewater Rafting
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
RezStream
 
Ooty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docxOoty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docx
Ooty Heritage Tours and Travels
 
Jose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlinJose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlin
MaryGraceArdalesLope
 
TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.
ujjwalsethi113
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
flyn goo
 
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto RicoExploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Caribbean Breeze Adventures
 
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdfLUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
Diper Tour
 
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
Bush Troop Safari
 
Get tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from LondonGet tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from London
London Country Tours
 
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdfAgence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
MICEboard
 
How To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdfHow To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdf
namechange763
 
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
bljeremy734
 
Winter Festivities in Italy
Winter Festivities in ItalyWinter Festivities in Italy
Winter Festivities in Italy
Time for Sicily
 
Understanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptxUnderstanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptx
Zivah ElectriVa Private Limited
 
Antarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonderAntarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonder
tahreemzahra82
 
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to VisitExploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Spade & Palacio Tours
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
pandeypratikwgblindi
 

Recently uploaded (18)

Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WAPaddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
 
Ooty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docxOoty Honeymoon Package from Chennai.docx
Ooty Honeymoon Package from Chennai.docx
 
Jose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlinJose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlin
 
TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
 
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto RicoExploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
 
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdfLUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
 
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
 
Get tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from LondonGet tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from London
 
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdfAgence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
 
How To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdfHow To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdf
 
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
 
Winter Festivities in Italy
Winter Festivities in ItalyWinter Festivities in Italy
Winter Festivities in Italy
 
Understanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptxUnderstanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptx
 
Antarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonderAntarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonder
 
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to VisitExploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
 

U3.stack queue

  • 2. What is a stack?  Stores a set of elements in a particular order  Stack principle: LAST IN FIRST OUT  = LIFO  It means: the last element inserted is the first one to be removed  Example  Which is the first element to pick up?
  • 3. Last In First Out top top E D D D C top C C C B top B B B B A A A A A A top
  • 4. Stack Applications  Real life  Pile of books, files, plates  TOH  More applications related to computer science  stack Program execution  Evaluating expressions  Palindrome finder  Parentheses matcher  A Palindrome is a string that reads the same in either direction  Examples: “Able was I ere I saw Elba”
  • 5. Stack objects: a finite ordered list with zero or more elements. methods: Stack createS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size Boolean isFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) return TRUE else return FALSE Stack push(stack, item) ::= if (IsFull(stack)) stack_full else insert item into top of stack and return
  • 6. Stack (cont’d) Boolean isEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSE Element pop(stack) ::= if(IsEmpty(stack)) return else remove and return the item on the top of the stack.
  • 7. Array-based Stack Implementation  Allocate an array of some size (pre-defined)  Maximum N elements in stack  Bottom stack element stored at element 0  last index in the array is the top  Increment top when one element is pushed, decrement after pop
  • 8. Stack Implementation  #include <stdio.h>  #include<conio.h>  # define MAXSIZE 200  int stack[MAXSIZE];  int top; //index pointing to the top of stack  void main()  {  void push(int);  int pop();  int will=1,i,num;  clrscr();  while(will ==1)  {  printf(" MAIN MENU:n 1.Add element to stackn2.Delete element from the stack");  scanf("%d",&will); 8 Chapter 5: Stacks
  • 9. switch(will)  {  case 1:  printf("Enter the data... ");  scanf("%d",&num);  push(num);  break;  case 2: i=pop();  printf("Value returned from pop function is %d ",i);  break;  default: printf("Invalid Choice . ");  }  printf(" Do you want to do more operations on Stack ( 1 for yes, any other key to exit) ");  scanf("%d" , &will);  } //end of outer while  } //end of main 9 Chapter 5: Stacks
  • 10. void push(int y)  {  if(top>MAXSIZE)  {  printf("nSTACK FULL");  return;  }  else  {  top++;  stack[top]=y;  }  } 10 Chapter 5: Stacks
  • 11. int pop()  {  int a;  if(top<=0)  {  printf("STACK EMPTY ");  return 0;  }  else  {  a=stack[top];  top--;  }  return(a);  } 11 Chapter 5: Stacks
  • 12. The Towers of Hanoi A Stack-based Application  GIVEN: three poles  a set of discs on the first pole, discs of different sizes, the smallest discs at the top  GOAL: move all the discs from the left pole to the right one.  CONDITIONS: only one disc may be moved at a time.  A disc can be placed either on an empty pole or on top of a larger disc.
  • 21. Polish(prefix) notation  - * / 15 - 7 + 1 1 3 + 2 + 1 1  = - * / 15 - 7 2 3 + 2 + 1 1  = - * / 15 5 3 + 2 + 1 1  =-*33+2+11  =-9+2+11  =-9+22  =-94  =5 An equivalent in-fix is as follows: ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5 21 Chapter 5: Stacks
  • 22. STACK OPERATIONS REVERSE POLISH NOTATION (postfix)  Reverse polish notation :is a postfix notation (places operators after operands)  (Example) Infix notation A+B Reverse Polish notation AB+ also called postfix.
  • 23. STACK OPERATIONS REVERSE POLISH NOTATION (postfix)  A stack organization is very effective for evaluating arithmetic expressions  A*B+C*D (AB *)+(CD *) AB * CD * +  (3*4)+(5*6) 34 * 56 * +
  • 24. STACK OPERATIONS REVERSE POLISH NOTATION (postfix) n • Evaluation procedure: n 1. Scan the expression from left to right. 2. When an operator is reached, perform the operation with the two operands found on the left side of the operator. 3. Replace the two operands and the operator by the result obtained from the operation. n (Example) infix 3 * 4 + 5 * 6 = 42 postfix 3 4 * 5 6 * + n 12 5 6 * + 12 30 + 42
  • 25. STACK OPERATIONS REVERSE POLISH NOTATION (postfix)  • Reverse Polish notation evaluation with a stack. Stack is the most efficient way for evaluating arithmetic expressions. stack evaluation: Get value If value is data: push data Else if value is operation: pop, pop evaluate and push.
  • 26. STACK OPERATIONS REVERSE POLISH NOTATION (postfix)  (Example) using stacks to do this. 3 * 4 + 5 * 6 = 42 => 3 4 * 5 6 * +
  • 28. The Queue Operations  A queue is like a line of people waiting for a bank teller. The queue has a front and a rear. $ $ Front Rear
  • 29. The Queue Operations  New people must enter the queue at the rear. The C++ queue class calls this a push, although it is usually called an enqueue operation. $ $ Front Rear
  • 30. The Queue Operations  When an item is taken from the queue, it always comes from the front. The C++ queue calls this a pop, although it is usually called a dequeue operation. $ $ Front Rear
  • 31. The Queue Class  The C++ template <class Item> standard class queue<Item> template library { has a queue public: template class. queue( ); void push(const Item&  The template entry); parameter is the void pop( ); type of the items bool empty( ) const; that can be put in Item front( ) const; the queue. …
  • 32. Array Implementation  A queue can be implemented with an array, as shown here. For example, this queue contains the integers 4 (at the front), 8 and 6 (at the rear). [0] [1] [2] [3] [4] [5] ... 4 8 6 An array of integers to implement a We don't care what's in queue of integers this part of the array.
  • 33. Array Implementation  The easiest implementation also 3 size keeps track of the number of items in the queue and the index of the first first 0 element (at the front of the queue), the last element (at the rear). 2 last [0] [1] [2] [3] [4] [5] ... 4 8 6
  • 34. A Dequeue Operation  When an element leaves the queue, 2 size size is decremented, and first changes, too. first 1 2 last [0] [1] [2] [3] [4] [5] ... 4 8 6
  • 35. An Enqueue Operation  When an element enters the queue, 3 size size is incremented, and last changes, too. first 1 3 last [0] [1] [2] [3] [4] [5] ... 8 6 2
  • 36. At the End of the Array  There is special behavior at the end 3 size of the array. For example, suppose we want to add a new element to this first 3 queue, where the last index is [5]: 5 last [0] [1] [2] [3] [4] [5] 2 6 1
  • 37. At the End of the Array  The new element goes at the front of 4 size the array (if that spot isn’t already used): first 3 0 last [0] [1] [2] [3] [4] [5] 4 2 6 1
  • 38. Array Implementation  Easy to implement 3 size  But it has a limited capacity with a fixed array  Or you must use a dynamic array for an 0 first unbounded capacity  Special behavior is needed when the rear 2 last reaches the end of the array. [0] [1] [2] [3] [4] [5] ... 4 8 6
  • 39. Linked List Implementation  A queue can also be implemented with a linked list with both a head and a tail 13 pointer. 15 10 7 null head_ptr tail_ptr
  • 40. Linked List Implementation  Which end do you think is the front of the queue? Why? 13 15 10 7 null head_ptr tail_ptr
  • 41. Linked List Implementation  The head_ptr points to the front of the list.  Because it is harder to remove Front 13 items from the tail of the list. 15 10 7 null head_ptr tail_ptr Rear
  • 42. A priority queue is a container in which access or deletion is of the highest- priority item, according to some way of Assigning priorities to items. 42 Priority Queues
  • 43. FOR EXAMPLE, SUPPOSE A HOSPITAL EMERGENCY ROOM HAS THE FOLLOWING FOUR PATIENTS, WITH NAME, PRIORITY, AND INJURY: 43 Priority Queues
  • 44. Matt 20 sprained ankle Andrew 45 broken leg Samira 20 high blood pressure Kerem 83 heart attack IN WHAT ORDER SHOULD THE PATIENTS BE TREATED? 44 Priority Queues
  • 45. THERE ARE MANY APPLICATIONS OF PRIORITY QUEUES, IN AREAS AS DIVERSE AS SCHEDULING, DATA COMPRESSION, AND JPEG (Joint Photographic Experts Group) ENCODING. 45 Priority Queues
  • 46. Using Priority Queue to Track Your Assignments  Organize class or work assignments by due dates  Early due date, higher priority  diagram of class Assignment