Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tonga Institute of Higher Education

Similar presentations


Presentation on theme: "Tonga Institute of Higher Education"— Presentation transcript:

1 Tonga Institute of Higher Education
Stacks Tonga Institute of Higher Education

2 The Mail Analogy When we get mail, we put all of our letters in a basket. Then, when we have time, we look at each letter starting from the top of the stack. After we process the letter, we put it away and look at the next one until we are at the bottom of the stack Warning: This “do the top one first” approach works well as long as you are able to process all the mail. If you can’t, there is a danger that letters on the bottom of the stack won’t be examined for months.

3 The Restaurant Analogy
Think of a stack of plates in a restaurant. When the plates are being stacked, they are added one on top of each other. It doesn't make much sense to put each plate on the bottom of the pile, as that would be far more work, and would accomplish nothing over stacking them on top of each other. Similarly when a plate is taken, it is usually taken from the top of the stack.

4 Definitions Stack – A data structure that stores a number of items. The last item entered into a stack is the first item to be removed Push – The act of adding an item to a stack Pop – The act of removing an item from the top of a stack Peek – The act of viewing the value of the item on top of the stack. Note: You cannot see the values for items under the top item. LIFO – Last in First Out – Sometimes used to describe a stack

5 Push - Add

6 Pop - Remove

7 Stack Implemented as an Array
1st in line 2nd in line 3rd in line 1 2 3 4 5 We can implement a stack using an array Each cell of the array represents a thing in the stack The bottom of stack is on the left The top of the stack is on the right

8 Stack Considerations Stack Size – Can be set when the stack is created
Errors: We try to push (add an item) when the stack is full We try to pop (remove an item) when the stack is empty

9 Presentation Stack Applet

10 Presentation Stack Code

11 Efficiency of Stacks Items can be pushed and popped in constant O(1) time This time is not dependent on the number of items in the stack so it is very fast No comparisons or moves are necessary


Download ppt "Tonga Institute of Higher Education"

Similar presentations


Ads by Google