Lecture 21 Stacks and Queues Richard Gesick
Stacks Implement a first-in-last-out behavior Push() to add an element Pop() to remove an element Add and remove from the same side of the internal data structure Easiest to add/remove from the front if implemented as a linked list internally Peek() returns the top element without removing it from the stack
Stacks C# stack is generic. Consider: Stack <string> myStack= new Stack>string>(); myStack.Push(“hello”); myStack.Push(“fun”); myStack.Push(“great”); Stack state? string t=myStack.Pop(); string s= myStack.Peek(); What is stored in s, t and what is left in the stack?
Stacks Which data structure would you pick to implement a Stack? Why?
Queues Implement a first-in-first-out behavior Enqueue() to add an element Dequeue() to remove an element Add and remove from the opposite sides of the internal data structure If we maintain a list-tail reference, then we can add to the end and remove from the front, each having constant - O(1) - time
Queues C# Queue is generic. Consider: State of the queue? Queue<int> q= new Queue<int>(); q.Enqueue(5); q.Enqueue(7); q.Enqueue(1); State of the queue? int a= q.Dequeue(); int b= q.Dequeue(); What is stored in a, b and what left in the queue?
Queues Which data structure would you pick to implement a Queue? Why?