Stacks and Queues Stacks and Queues Not really

  • Slides: 28
Download presentation
Stacks and Queues

Stacks and Queues

Stacks and Queues • Not really “data structures” – More of an enforcement of

Stacks and Queues • Not really “data structures” – More of an enforcement of policy – Can be implemented using an array or linked list – Can store just about any kind of data • Queues – First In, First Out (FIFO) – Like waiting in line • Stacks – First In, Last Out (FILO) – Like a stack of trays

Stacks • Three primary operations – Push() – put new data on the top

Stacks • Three primary operations – Push() – put new data on the top of the stack – Pop() – remove data from the top of the stack – Peek() – get a copy of the data on the top of the stack • Useful – our function stack! – stack of cards, tiles, loot, etc…

Example (pushing) 5 Note: could use a linked list also

Example (pushing) 5 Note: could use a linked list also

Example (pushing) 11 5

Example (pushing) 11 5

Example (pushing) -6 11 5

Example (pushing) -6 11 5

Example (pushing) 45 -6 11 5

Example (pushing) 45 -6 11 5

Example (current stack) 45 -6 11 5

Example (current stack) 45 -6 11 5

Example (peeking) 45 45 -6 11 5

Example (peeking) 45 45 -6 11 5

Example (popping) 45 -6 11 5

Example (popping) 45 -6 11 5

Example (pushing) 31 -6 11 5

Example (pushing) 31 -6 11 5

Example (popping) 31 -6 11 5

Example (popping) 31 -6 11 5

Example (popping) -6 11 5

Example (popping) -6 11 5

Example (popping) 11 5

Example (popping) 11 5

Example (popping) FILO 5

Example (popping) FILO 5

Queues • Two primary operations – Enqueue() – put new data at the end

Queues • Two primary operations – Enqueue() – put new data at the end of the queue – Dequeue() – remove data from the beginning of the queue – Peek() – yes, it’s still there… • Useful – Enforcing fairness (waitlist at SPSU) – Player turns during a round

Example

Example

Example (enqueue a 5) 5

Example (enqueue a 5) 5

Example 5

Example 5

Example (enqueue an 11) 5 11

Example (enqueue an 11) 5 11

Example 5 11

Example 5 11

Example (enqueue a -6) 5 11 -6

Example (enqueue a -6) 5 11 -6

Example 5 11 -6

Example 5 11 -6

Example (dequeue) 5 11 -6

Example (dequeue) 5 11 -6

Example (dequeue) 5 11 -6

Example (dequeue) 5 11 -6

Example (dequeue) 5 11 -6 FIFO

Example (dequeue) 5 11 -6 FIFO

Example (dequeue) 11 -6

Example (dequeue) 11 -6

Summary • Not really “data structures” – More of an enforcement of policy –

Summary • Not really “data structures” – More of an enforcement of policy – Can be implemented using an array or linked list • • Queues are FIFO Stacks are FILO Which data structure is LILO? Which one is LIFO?