SlideShare a Scribd company logo
1 of 36
Download to read offline
Stacks and Queues

                                 Dr.Haitham A. El-Ghareeb

                                  Information Systems Department
                           Faculty of Computers and Information Sciences
                                        Mansoura University
                                       helghareeb@gmail.com


                                       October 21, 2012




Dr.Haitham A. El-Ghareeb (CIS)     Data Structures and Algorithms - 2012   October 21, 2012   1 / 31
Stacks and Queues




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   2 / 31
Stacks and Queues
     Data in a stack are added and removed from only one end of the list.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   2 / 31
Stacks and Queues
     Data in a stack are added and removed from only one end of the list.
     Data in a queue are added at one end and removed from the other
     end of a list.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   2 / 31
Stacks and Queues
     Data in a stack are added and removed from only one end of the list.
     Data in a queue are added at one end and removed from the other
     end of a list.
     Stacks are used extensively in programming language
     implementations, from everything from expression evaluation to
     handling function calls.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   2 / 31
Stacks and Queues
     Data in a stack are added and removed from only one end of the list.
     Data in a queue are added at one end and removed from the other
     end of a list.
     Stacks are used extensively in programming language
     implementations, from everything from expression evaluation to
     handling function calls.
     Queues are used to prioritize operating system processes and to
     simulate events in the real world, such as teller lines at banks and the
     operation of elevators in buildings.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   2 / 31
Stacks and Queues
     Data in a stack are added and removed from only one end of the list.
     Data in a queue are added at one end and removed from the other
     end of a list.
     Stacks are used extensively in programming language
     implementations, from everything from expression evaluation to
     handling function calls.
     Queues are used to prioritize operating system processes and to
     simulate events in the real world, such as teller lines at banks and the
     operation of elevators in buildings.
     C# provides two classes for using these data structures: the Stack
     class and the Queue class.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   2 / 31
Stacks
     One of the most frequently used data structures.
     Stack is a list of items that are accessible only from the end of the
     list, which is called the top of the stack. Known as a Last-in,
     First-out (LIFO) data structure.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   3 / 31
Stack Operations
The two primary operations of a stack are adding items to the stack and
taking items off the stack.
      The Push operation adds an item to a stack.
      We take an item off the stack with a Pop operation.
      The other primary operation to perform on a stack is viewing the top
      item (Peek). The Pop operation returns the top item, but the
      operation also removes it from the stack.
      A stack is completed emptied by calling the Clear operation.
      t is also useful to know how many items are in a stack at any one
      time. We do this by calling the Count property.




 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   4 / 31
Stack Operations (Cont.)




                  Figure: Stack Two Main Operations: Push, and Pop




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   5 / 31
Stack Constructors
     Stack(): Initializes a new instance of the Stack class that is empty
     and has the default initial capacity.
     Stack(ICollection): Initializes a new instance of the Stack class that
     contains elements copied from the specified collection and has the
     same initial capacity as the number of elements copied.
     Stack(Int32): Initializes a new instance of the Stack class that is
     empty and has the specified initial capacity or the default initial
     capacity, whichever is greater.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   6 / 31
Stack Properties
      Count: Gets the number of elements contained in the Stack.
      IsSynchronized: Gets a value indicating whether access to the Stack is
      synchronized (thread safe).
      SyncRoot: Gets an object that can be used to synchronize access to
      the Stack.




 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   7 / 31
Stack Properties
      Clear: Removes all objects from the Stack.
      Clone: Creates a shallow copy of the Stack.
      Contains: Determines whether an element is in the Stack.
      CopyTo: Copies the Stack to an existing one-dimensional Array,
      starting at the specified array index.
      Equals(Object): Determines whether the specified object is equal to
      the current object. (Inherited from Object.)
      Finalize: Allows an object to try to free resources and perform other
      cleanup operations before it is reclaimed by garbage collection.
      (Inherited from Object.)
      GetEnumerator: Returns an IEnumerator for the Stack.




 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   8 / 31
Stack Properties (Cont.)
      GetHashCode: Serves as a hash function for a particular type.
      (Inherited from Object.)
      GetType: Gets the Type of the current instance. (Inherited from
      Object.)
      MemberwiseClone: Creates a shallow copy of the current Object.
      (Inherited from Object.)
      Peek: Returns the object at the top of the Stack without removing it.
      Pop: Removes and returns the object at the top of the Stack.
      Push: Inserts an object at the top of the Stack.
      Synchronized: Returns a synchronized (thread safe) wrapper for the
      Stack.
      ToArray: Copies the Stack to a new array.
      ToString: Returns a string that represents the current object.
      (Inherited from Object.)

 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   9 / 31
Stack Remarks
     Stack is implemented as a circular buffer.
     The capacity of a Stack is the number of elements the Stack can
     hold. As elements are added to a Stack, the capacity is automatically
     increased as required through reallocation.
     If Count is less than the capacity of the stack, Push is an O(1)
     operation. If the capacity needs to be increased to accommodate the
     new element, Push becomes an O(n) operation, where n is Count.
     Pop is an O(1) operation.
     Stack accepts null as a valid value and allows duplicate elements.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   10 / 31
Stack Example

using System ;
using System . Collections ;
public class SamplesStack {
    public static void Main ( ) {
       // Creates and initializes a new Stack .
       Stack myStack = new Stack ( ) ;
       myStack . Push ( ” H e l l o ” ) ;
       myStack . Push ( ” World ” ) ;
       myStack . Push ( ” ! ” ) ;

          // Displays the properties and values of the Stack .
          Console . WriteLine ( ” myStack ” ) ;
          Console . WriteLine ( ”  t C o u n t :     {0} ” , myStack . Count ) ;
          Console . Write ( ”  t V a l u e s : ” ) ;
          PrintValues ( myStack ) ;
     }

     public static void PrintValues ( IEnumerable myCollection )                            {
        f o r e a c h ( Object obj in myCollection )
              Console . Write ( ”    {0} ” , obj ) ;
        Console . WriteLine ( ) ;
     }
}
Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   11 / 31
Building Our Own Stack

class CStack {
private int p_index ;
private ArrayList list ;
public CStack ( ) {
list = new ArrayList ( ) ;
p_index = −1;
}
public int count {
get {
      return list . Count ;
      }
    }
    public void push ( object item ) {
      list . Add ( item ) ;
      p_index++;
    }




 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   12 / 31
Building Our Own Stack (Cont.)

         public object pop ( ) {
           object obj = list [ p_index ] ;
           list . RemoveAt ( p_index ) ;
           p_index −−;
           return obj ;
         }
         public void clear ( ) {
           list . Clear ( ) ;
           p_index = −1;
         }
         public object peek ( ) {
           return list [ p_index ] ;
         }
}




    Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   13 / 31
Using Our Own Code

static void Main ( string [ ] args ) {
CStack alist = new CStack ( ) ;
string ch ;
string word = ” s e e s ” ;
bool isPalindrome = true ;
for ( int x = 0 ; x < word . Length ; x++)
alist . push ( word . Substring ( x , 1 ) ) ;
int pos = 0 ;
w h i l e ( alist . count > 0 ) {
ch = alist . pop ( ) . ToString ( ) ;
i f ( ch != word . Substring ( pos , 1 ) ) {
     isPalindrome = false ;
break ;
}
pos++;
}
        i f ( isPalindrome )
          Console . WriteLine ( word + ” i s a p a l i n d r o m e . ” ) ;
        else
          Console . WriteLine ( word + ” i s n o t a p a l i n d r o m e . ” ) ;
        Console . Read ( ) ;
}

 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012     October 21, 2012   14 / 31
Task
                           Decimal to Multiple-Base Conversion




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   15 / 31
Queues
     Queue is a data structure where data enters at the rear of a list and is
     removed from the front of the list.
     Queues are used to store items in the order in which they occur.
     Queues are an example of a first-in, first-out (FIFO) data structure.
     Queues are used to order processes submitted to an operating system
     or a print spooler, and simulation applications use queues to model
     customers waiting in a line.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   16 / 31
Queue Constructors
     Queue( ): Initializes a new instance of the Queue class that is empty,
     has the default initial capacity, and uses the default growth factor.
     Queue(ICollection): Initializes a new instance of the Queue class that
     contains elements copied from the specified collection, has the same
     initial capacity as the number of elements copied, and uses the
     default growth factor.
     Queue(Int32): Initializes a new instance of the Queue class that is
     empty, has the specified initial capacity, and uses the default growth
     factor.
     Queue(Int32, Single): Initializes a new instance of the Queue class
     that is empty, has the specified initial capacity, and uses the specified
     growth factor.



Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   17 / 31
Queue Properties
     Count: Gets the number of elements contained in the Queue.
     IsSynchronized: Gets a value indicating whether access to the Queue
     is synchronized (thread safe).
     SyncRoot: Gets an object that can be used to synchronize access to
     the Queue.




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   18 / 31
Queue Methods
     Clear: Removes all objects from the Queue.
     Clone: Creates a shallow copy of the Queue.
     Contains: Determines whether an element is in the Queue.
     CopyTo: Copies the Queue elements to an existing one-dimensional
     Array, starting at the specified array index.
     Dequeue: Removes and returns the object at the beginning of the
     Queue.
     Enqueue: Adds an object to the end of the Queue.
     Equals(Object): Determines whether the specified object is equal to
     the current object. (Inherited from Object.)
     Finalize: Allows an object to try to free resources and perform other
     cleanup operations before it is reclaimed by garbage collection.



Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   19 / 31
Queue Methods (Cont.)
     GetEnumerator: Returns an enumerator that iterates through the
     Queue.
     GetHashCode: Serves as a hash function for a particular type.
     (Inherited from Object.)
     GetType: Gets the Type of the current instance. (Inherited from
     Object.)
     MemberwiseClone: Creates a shallow copy of the current Object.
     (Inherited from Object.)
     Peek: Returns the object at the beginning of the Queue without
     removing it.
     Synchronized: Returns a Queue wrapper that is synchronized (thread
     safe).
     ToArray: Copies the Queue elements to a new array.
     ToString: Returns a string that represents the current object.
     (Inherited from Object.)
     TrimToSize Sets the capacity to the actual number of elements in the
Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   20 / 31
Queue Remarks
     Queues are useful for storing messages in the order they were received
     for sequential processing. This class implements a queue as a circular
     array. Objects stored in a Queue are inserted at one end and removed
     from the other.
     The capacity of a Queue is the number of elements the Queue can
     hold. As elements are added to a Queue, the capacity is automatically
     increased as required through reallocation. The capacity can be
     decreased by calling TrimToSize.
     The growth factor is the number by which the current capacity is
     multiplied when a greater capacity is required. The growth factor is
     determined when the Queue is constructed. The default growth factor
     is 2.0. The capacity of the Queue will always increase by at least a
     minimum of four, regardless of the growth factor. For example, a
     Queue with a growth factor of 1.0 will always increase in capacity by
     four when a greater capacity is required.
     Queue accepts null as a valid value and allows duplicate elements.
Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   21 / 31
Queue Example

using System ;
using System . Collections ;
public class SamplesQueue                {

     public static void Main ( )               {

          // Creates and initializes a new Queue .
          Queue myQ = new Queue ( ) ;
          myQ . Enqueue ( ” H e l l o ” ) ;
          myQ . Enqueue ( ” World ” ) ;
          myQ . Enqueue ( ” ! ” ) ;

          // Displays the properties and values of the Queue .
          Console . WriteLine ( ”myQ” ) ;
          Console . WriteLine ( ”  t C o u n t :     {0} ” , myQ . Count ) ;
          Console . Write ( ”  t V a l u e s : ” ) ;
          PrintValues ( myQ ) ;
     }
}



Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   22 / 31
Queue Example (Cont.)

public static void PrintValues ( IEnumerable myCollection )                           {
       f o r e a c h ( Object obj in myCollection )
             Console . Write ( ”    {0} ” , obj ) ;
       Console . WriteLine ( ) ;
    }




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   23 / 31
Two Queue Approaches
     First come, first served
     Priority-based processing




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   24 / 31
Memory Management of Queues




                  Figure: The ArrayList after the first two lines of code




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   25 / 31
Memory Management of Queues




              Figure: Program after the GetNextJob() method is invoked




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   26 / 31
Memory Management of Queues




                   Figure: Issue Created by placing jobs in the 0 index




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   27 / 31
Memory Management of Queues




                                 Figure: Example of a Circular Array
Dr.Haitham A. El-Ghareeb (CIS)        Data Structures and Algorithms - 2012   October 21, 2012   28 / 31
Queue Operations
     Enqueu
     Dequeu




                                 Figure: Queue Operations

Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   29 / 31
Priority Queues
      For many applications, a data structure is needed where an item with
      the highest priority is removed first, even if it isnt the oldest item in
      the structure.
      There are many applications that utilize priority queues in their
      operations.
      A good example is process handling in a computer operating system.
      Certain processes have a higher priority than other processes, such as
      printing processes, which typically have a low priority.
      Processes (or tasks) are usually numbered by their priority, with a
      Priority 0 process having a higher priority than a Priority 20 task.
      Items stored in a priority queue are normally constructed as keyvalue
      pairs, where the key is the priority level and the value identifies the
      item.


 Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   30 / 31
Happy Eid




Dr.Haitham A. El-Ghareeb (CIS)   Data Structures and Algorithms - 2012   October 21, 2012   31 / 31

More Related Content

What's hot

What's hot (20)

Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 
Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
Abstract data types (adt) intro to data structure part 2
Abstract data types (adt)   intro to data structure part 2Abstract data types (adt)   intro to data structure part 2
Abstract data types (adt) intro to data structure part 2
 
Data structure using c++
Data structure using c++Data structure using c++
Data structure using c++
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
 
Data structures
Data structuresData structures
Data structures
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structure
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Introduction to data structure and algorithms
Introduction to data structure and algorithmsIntroduction to data structure and algorithms
Introduction to data structure and algorithms
 
R training2
R training2R training2
R training2
 
Stacks in algorithems & data structure
Stacks in algorithems & data structureStacks in algorithems & data structure
Stacks in algorithems & data structure
 

Similar to Lecture-05-DSA

Topic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.pptTopic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.pptBlackSeraph
 
Topic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.pptTopic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.pptMeenakshiPatel13
 
Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases MongoDB
 
Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL DatabasesReal-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL DatabasesEugene Dvorkin
 
Collections generic
Collections genericCollections generic
Collections genericsandhish
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
SQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail Science
SQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail ScienceSQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail Science
SQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail ScienceUniversity of Washington
 
Lecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzadLecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzadAtif Shahzad
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 
ElasticSearch.pptx
ElasticSearch.pptxElasticSearch.pptx
ElasticSearch.pptxTrnHiu748002
 
3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#SyedUmairAli9
 
L1 - Recap.pdf
L1 - Recap.pdfL1 - Recap.pdf
L1 - Recap.pdfIfat Nix
 

Similar to Lecture-05-DSA (20)

Topic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.pptTopic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.ppt
 
Topic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.pptTopic12ADTS_GenericDataStructures.ppt
Topic12ADTS_GenericDataStructures.ppt
 
Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases
 
Collections
CollectionsCollections
Collections
 
Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL DatabasesReal-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases
 
Collections generic
Collections genericCollections generic
Collections generic
 
Lect1.pptx
Lect1.pptxLect1.pptx
Lect1.pptx
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
SQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail Science
SQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail ScienceSQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail Science
SQL is Dead; Long Live SQL: Lightweight Query Services for Long Tail Science
 
Lecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzadLecture08 computer applicationsie1_dratifshahzad
Lecture08 computer applicationsie1_dratifshahzad
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
 
Lec2
Lec2Lec2
Lec2
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
ElasticSearch.pptx
ElasticSearch.pptxElasticSearch.pptx
ElasticSearch.pptx
 
Unit-I.pdf
Unit-I.pdfUnit-I.pdf
Unit-I.pdf
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 
3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil3. Stack - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
L1 - Recap.pdf
L1 - Recap.pdfL1 - Recap.pdf
L1 - Recap.pdf
 

More from Haitham El-Ghareeb

More from Haitham El-Ghareeb (20)

مختصر وحدة التعلم الذاتي 2015
مختصر وحدة التعلم الذاتي 2015مختصر وحدة التعلم الذاتي 2015
مختصر وحدة التعلم الذاتي 2015
 
وحدة التعلم الذاتي 2015
وحدة التعلم الذاتي 2015وحدة التعلم الذاتي 2015
وحدة التعلم الذاتي 2015
 
NoSQL Databases, Not just a Buzzword
NoSQL Databases, Not just a Buzzword NoSQL Databases, Not just a Buzzword
NoSQL Databases, Not just a Buzzword
 
EMC Academic Alliance Presentation
EMC Academic Alliance PresentationEMC Academic Alliance Presentation
EMC Academic Alliance Presentation
 
DSA - 2012 - Conclusion
DSA - 2012 - ConclusionDSA - 2012 - Conclusion
DSA - 2012 - Conclusion
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data Structures
 
Data Structures - Lecture 8 - Study Notes
Data Structures - Lecture 8 - Study NotesData Structures - Lecture 8 - Study Notes
Data Structures - Lecture 8 - Study Notes
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
LectureNotes-04-DSA
LectureNotes-04-DSALectureNotes-04-DSA
LectureNotes-04-DSA
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
LectureNotes-01-DSA
LectureNotes-01-DSALectureNotes-01-DSA
LectureNotes-01-DSA
 
Learn Latex
Learn LatexLearn Latex
Learn Latex
 
Research Methodologies - Lecture 02
Research Methodologies - Lecture 02Research Methodologies - Lecture 02
Research Methodologies - Lecture 02
 
DSA - Lecture 03
DSA - Lecture 03DSA - Lecture 03
DSA - Lecture 03
 
Ph.D. Registeration seminar
Ph.D. Registeration seminarPh.D. Registeration seminar
Ph.D. Registeration seminar
 
Lecture 01 - Research Methods
Lecture 01 - Research MethodsLecture 01 - Research Methods
Lecture 01 - Research Methods
 
Lecture 02 - DSA
Lecture 02 - DSALecture 02 - DSA
Lecture 02 - DSA
 
DSA-2012-Lect00
DSA-2012-Lect00DSA-2012-Lect00
DSA-2012-Lect00
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Lecture-05-DSA

  • 1. Stacks and Queues Dr.Haitham A. El-Ghareeb Information Systems Department Faculty of Computers and Information Sciences Mansoura University helghareeb@gmail.com October 21, 2012 Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 1 / 31
  • 2. Stacks and Queues Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 2 / 31
  • 3. Stacks and Queues Data in a stack are added and removed from only one end of the list. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 2 / 31
  • 4. Stacks and Queues Data in a stack are added and removed from only one end of the list. Data in a queue are added at one end and removed from the other end of a list. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 2 / 31
  • 5. Stacks and Queues Data in a stack are added and removed from only one end of the list. Data in a queue are added at one end and removed from the other end of a list. Stacks are used extensively in programming language implementations, from everything from expression evaluation to handling function calls. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 2 / 31
  • 6. Stacks and Queues Data in a stack are added and removed from only one end of the list. Data in a queue are added at one end and removed from the other end of a list. Stacks are used extensively in programming language implementations, from everything from expression evaluation to handling function calls. Queues are used to prioritize operating system processes and to simulate events in the real world, such as teller lines at banks and the operation of elevators in buildings. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 2 / 31
  • 7. Stacks and Queues Data in a stack are added and removed from only one end of the list. Data in a queue are added at one end and removed from the other end of a list. Stacks are used extensively in programming language implementations, from everything from expression evaluation to handling function calls. Queues are used to prioritize operating system processes and to simulate events in the real world, such as teller lines at banks and the operation of elevators in buildings. C# provides two classes for using these data structures: the Stack class and the Queue class. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 2 / 31
  • 8. Stacks One of the most frequently used data structures. Stack is a list of items that are accessible only from the end of the list, which is called the top of the stack. Known as a Last-in, First-out (LIFO) data structure. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 3 / 31
  • 9. Stack Operations The two primary operations of a stack are adding items to the stack and taking items off the stack. The Push operation adds an item to a stack. We take an item off the stack with a Pop operation. The other primary operation to perform on a stack is viewing the top item (Peek). The Pop operation returns the top item, but the operation also removes it from the stack. A stack is completed emptied by calling the Clear operation. t is also useful to know how many items are in a stack at any one time. We do this by calling the Count property. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 4 / 31
  • 10. Stack Operations (Cont.) Figure: Stack Two Main Operations: Push, and Pop Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 5 / 31
  • 11. Stack Constructors Stack(): Initializes a new instance of the Stack class that is empty and has the default initial capacity. Stack(ICollection): Initializes a new instance of the Stack class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied. Stack(Int32): Initializes a new instance of the Stack class that is empty and has the specified initial capacity or the default initial capacity, whichever is greater. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 6 / 31
  • 12. Stack Properties Count: Gets the number of elements contained in the Stack. IsSynchronized: Gets a value indicating whether access to the Stack is synchronized (thread safe). SyncRoot: Gets an object that can be used to synchronize access to the Stack. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 7 / 31
  • 13. Stack Properties Clear: Removes all objects from the Stack. Clone: Creates a shallow copy of the Stack. Contains: Determines whether an element is in the Stack. CopyTo: Copies the Stack to an existing one-dimensional Array, starting at the specified array index. Equals(Object): Determines whether the specified object is equal to the current object. (Inherited from Object.) Finalize: Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) GetEnumerator: Returns an IEnumerator for the Stack. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 8 / 31
  • 14. Stack Properties (Cont.) GetHashCode: Serves as a hash function for a particular type. (Inherited from Object.) GetType: Gets the Type of the current instance. (Inherited from Object.) MemberwiseClone: Creates a shallow copy of the current Object. (Inherited from Object.) Peek: Returns the object at the top of the Stack without removing it. Pop: Removes and returns the object at the top of the Stack. Push: Inserts an object at the top of the Stack. Synchronized: Returns a synchronized (thread safe) wrapper for the Stack. ToArray: Copies the Stack to a new array. ToString: Returns a string that represents the current object. (Inherited from Object.) Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 9 / 31
  • 15. Stack Remarks Stack is implemented as a circular buffer. The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. Stack accepts null as a valid value and allows duplicate elements. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 10 / 31
  • 16. Stack Example using System ; using System . Collections ; public class SamplesStack { public static void Main ( ) { // Creates and initializes a new Stack . Stack myStack = new Stack ( ) ; myStack . Push ( ” H e l l o ” ) ; myStack . Push ( ” World ” ) ; myStack . Push ( ” ! ” ) ; // Displays the properties and values of the Stack . Console . WriteLine ( ” myStack ” ) ; Console . WriteLine ( ” t C o u n t : {0} ” , myStack . Count ) ; Console . Write ( ” t V a l u e s : ” ) ; PrintValues ( myStack ) ; } public static void PrintValues ( IEnumerable myCollection ) { f o r e a c h ( Object obj in myCollection ) Console . Write ( ” {0} ” , obj ) ; Console . WriteLine ( ) ; } } Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 11 / 31
  • 17. Building Our Own Stack class CStack { private int p_index ; private ArrayList list ; public CStack ( ) { list = new ArrayList ( ) ; p_index = −1; } public int count { get { return list . Count ; } } public void push ( object item ) { list . Add ( item ) ; p_index++; } Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 12 / 31
  • 18. Building Our Own Stack (Cont.) public object pop ( ) { object obj = list [ p_index ] ; list . RemoveAt ( p_index ) ; p_index −−; return obj ; } public void clear ( ) { list . Clear ( ) ; p_index = −1; } public object peek ( ) { return list [ p_index ] ; } } Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 13 / 31
  • 19. Using Our Own Code static void Main ( string [ ] args ) { CStack alist = new CStack ( ) ; string ch ; string word = ” s e e s ” ; bool isPalindrome = true ; for ( int x = 0 ; x < word . Length ; x++) alist . push ( word . Substring ( x , 1 ) ) ; int pos = 0 ; w h i l e ( alist . count > 0 ) { ch = alist . pop ( ) . ToString ( ) ; i f ( ch != word . Substring ( pos , 1 ) ) { isPalindrome = false ; break ; } pos++; } i f ( isPalindrome ) Console . WriteLine ( word + ” i s a p a l i n d r o m e . ” ) ; else Console . WriteLine ( word + ” i s n o t a p a l i n d r o m e . ” ) ; Console . Read ( ) ; } Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 14 / 31
  • 20. Task Decimal to Multiple-Base Conversion Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 15 / 31
  • 21. Queues Queue is a data structure where data enters at the rear of a list and is removed from the front of the list. Queues are used to store items in the order in which they occur. Queues are an example of a first-in, first-out (FIFO) data structure. Queues are used to order processes submitted to an operating system or a print spooler, and simulation applications use queues to model customers waiting in a line. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 16 / 31
  • 22. Queue Constructors Queue( ): Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default growth factor. Queue(ICollection): Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor. Queue(Int32): Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor. Queue(Int32, Single): Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 17 / 31
  • 23. Queue Properties Count: Gets the number of elements contained in the Queue. IsSynchronized: Gets a value indicating whether access to the Queue is synchronized (thread safe). SyncRoot: Gets an object that can be used to synchronize access to the Queue. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 18 / 31
  • 24. Queue Methods Clear: Removes all objects from the Queue. Clone: Creates a shallow copy of the Queue. Contains: Determines whether an element is in the Queue. CopyTo: Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index. Dequeue: Removes and returns the object at the beginning of the Queue. Enqueue: Adds an object to the end of the Queue. Equals(Object): Determines whether the specified object is equal to the current object. (Inherited from Object.) Finalize: Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 19 / 31
  • 25. Queue Methods (Cont.) GetEnumerator: Returns an enumerator that iterates through the Queue. GetHashCode: Serves as a hash function for a particular type. (Inherited from Object.) GetType: Gets the Type of the current instance. (Inherited from Object.) MemberwiseClone: Creates a shallow copy of the current Object. (Inherited from Object.) Peek: Returns the object at the beginning of the Queue without removing it. Synchronized: Returns a Queue wrapper that is synchronized (thread safe). ToArray: Copies the Queue elements to a new array. ToString: Returns a string that represents the current object. (Inherited from Object.) TrimToSize Sets the capacity to the actual number of elements in the Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 20 / 31
  • 26. Queue Remarks Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize. The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. The default growth factor is 2.0. The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required. Queue accepts null as a valid value and allows duplicate elements. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 21 / 31
  • 27. Queue Example using System ; using System . Collections ; public class SamplesQueue { public static void Main ( ) { // Creates and initializes a new Queue . Queue myQ = new Queue ( ) ; myQ . Enqueue ( ” H e l l o ” ) ; myQ . Enqueue ( ” World ” ) ; myQ . Enqueue ( ” ! ” ) ; // Displays the properties and values of the Queue . Console . WriteLine ( ”myQ” ) ; Console . WriteLine ( ” t C o u n t : {0} ” , myQ . Count ) ; Console . Write ( ” t V a l u e s : ” ) ; PrintValues ( myQ ) ; } } Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 22 / 31
  • 28. Queue Example (Cont.) public static void PrintValues ( IEnumerable myCollection ) { f o r e a c h ( Object obj in myCollection ) Console . Write ( ” {0} ” , obj ) ; Console . WriteLine ( ) ; } Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 23 / 31
  • 29. Two Queue Approaches First come, first served Priority-based processing Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 24 / 31
  • 30. Memory Management of Queues Figure: The ArrayList after the first two lines of code Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 25 / 31
  • 31. Memory Management of Queues Figure: Program after the GetNextJob() method is invoked Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 26 / 31
  • 32. Memory Management of Queues Figure: Issue Created by placing jobs in the 0 index Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 27 / 31
  • 33. Memory Management of Queues Figure: Example of a Circular Array Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 28 / 31
  • 34. Queue Operations Enqueu Dequeu Figure: Queue Operations Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 29 / 31
  • 35. Priority Queues For many applications, a data structure is needed where an item with the highest priority is removed first, even if it isnt the oldest item in the structure. There are many applications that utilize priority queues in their operations. A good example is process handling in a computer operating system. Certain processes have a higher priority than other processes, such as printing processes, which typically have a low priority. Processes (or tasks) are usually numbered by their priority, with a Priority 0 process having a higher priority than a Priority 20 task. Items stored in a priority queue are normally constructed as keyvalue pairs, where the key is the priority level and the value identifies the item. Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 30 / 31
  • 36. Happy Eid Dr.Haitham A. El-Ghareeb (CIS) Data Structures and Algorithms - 2012 October 21, 2012 31 / 31