Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 16 Stacks and Queues Richard Gesick. Sample test questions 1.Write a definition for a Node class that holds a number. 2.Write a method that sums.

Similar presentations


Presentation on theme: "Lecture 16 Stacks and Queues Richard Gesick. Sample test questions 1.Write a definition for a Node class that holds a number. 2.Write a method that sums."— Presentation transcript:

1 Lecture 16 Stacks and Queues Richard Gesick

2 Sample test questions 1.Write a definition for a Node class that holds a number. 2.Write a method that sums up all of the numbers held within a linked list and returns the sum 14-2

3 Question 1 class Node { public int Data; public Node Next; } 14-3

4 Question 2 int Sum(Node current) { if (current == null) return 0; else return current.Data + Sum(current.Next); } int Sum(Node current) { int s = 0; while (current != null) { s += current.Data; current = current.Next; } return s; } 14-4

5 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 popping it from the stack 14-5

6 Stacks Which data structure would you pick to implement a Stack? Why? 14-6

7 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 14-7

8 Queues Which data structure would you pick to implement a Queue? Why? 14-8


Download ppt "Lecture 16 Stacks and Queues Richard Gesick. Sample test questions 1.Write a definition for a Node class that holds a number. 2.Write a method that sums."

Similar presentations


Ads by Google