Stacks Queues

advertisement

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 up all of the numbers held within a linked list and returns the sum

14-2

Question 1

class Node

{ public int Data; public Node Next;

}

14-3

int Sum(Node current)

{ if (current == null) return 0; else return current.Data +

Sum(current.Next);

}

Question 2

int Sum(Node current)

{ int s = 0; while (current != null)

{ s += current.Data; current = current.Next;

} return s;

}

14-4

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

Stacks

• Which data structure would you pick to implement a Stack? Why?

14-6

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

Queues

• Which data structure would you pick to implement a Queue? Why?

14-8

Download