180 likes | 300 Views
CSE 2341 - Honors Principles of Computer Science I. Spring 2008 Mark Fontenot mfonten@engr.smu.edu. Note Set 15. Overview. Stacks Queues. The Stack. STACK data structure that stores and retrieves items in a last-in-first-out manner only have access to element “on top” of the stack
E N D
CSE 2341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 15
Overview Stacks Queues
The Stack • STACK • data structure that stores and retrieves items in a last-in-first-out manner • only have access to element “on top” of the stack • How is this different from a basic array?
Stack last in first out 5 4 3 2 1 last out first in Think of a stack of plates in a cafeteria
Applications of Stacks Used during program execution Can use a stack to perform mathematical operations general: useful data structure for any algorithms that work with the last saved element of a series.
2 Types • Static Stacks • Fixed size • Implemented as Arrays • Dynamic Stacks • ability to grow and shrink as needed. • Implemented as Linked lists
Basic Stack Operations Empty Stack push(5) push(10) push(7) 5 10 7 5 10 5 • push(x) • causes a value to be stored or pushed onto the stack
Basic Stack Operations 10 5 7 10 5 pop(x) 5 pop(x) pop(x) • pop(x) • retrieves (and hence, removes) a value from the stack.
Basic Stack Operations • isFull() • boolean function needed with fixed-size stacks • prevents stack overflow from trying to push a value on when there is no more room • isEmpty() • boolean function needed for both fixed and dynamic stacks • prevents any errors from the pop operation on an empty stack.
The Queue • queue • data structure that stores and retrieves items in a first-in-first-out manner • Elements are added to the rear and removed from the front
Queue rear front Think of a line of people waiting to check out
Applications of Queue Operating systems use queues to keep track of processes that are executing and in which order they are allowed to use the processor Printing queues Communications
2 Types • Static queues • Fixed size • Implemented as Arrays • Dynamic queues • ability to grow and shrink as needed. • Implemented as Linked lists
Basic Queue Operations Empty Queue Front Rear 5 enqueue(5) 5 10 enqueue(10) Front Rear 10 5 7 enqueue(7) • enqueue(x) • causes a value to be stored in the queue
Basic Queue Operations 5 dequeue() 10 7 10 dequeue() 7 • dequeue() • causes a value to be removed from the queue
Problem • With static queue • Every dequeue operation requires the elements behind it to move “forward” – very expensive • Can overcome by allowing both front and rear indices to move but possible to run out of room in the array • Over come by using a circular array OR dynamic queue.
DynamicQueue class DynIntQueue { private: struct queueNode { int val; queueNode* next; }; queueNode* front; queueNode* rear; public: //See handout! }; 3 4 5 Null Front Rear
Fini ?