This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: COMP 250 Winter 2010 lecture 7 stacks January 20, 2010 Stack ADT In this lecture and the next, we look at stacks and queues. Each is an ordered set of objects (a list), where the ordering is determined by when each object was inserted. With a stack, one accesses/removes the newest element (most recently added) whereas with a queue, one ac- cesses/removes the oldest element (least recently inserted). Today we look at stacks. You are familiar with stacks in your everyday life. You can have a stack of books on a table. You can have a stack of plates on a shelf. In computer science, a stack is an abstract data type (ADT) with two operations: push and pop . You either push something onto the top of the stack or you pop the element that is on the top of the stack. A more elaborate ADT for the stack might allow you to check if the stack has any items in it ( isEmpty ) or to examine the top element without popping it ( top , also known as peek ) or to ask how many elements there are ( size ). But these operations not necessary for us to call something a stack. We are familiar with stacks of things/objects. We are also familar with stacks of tasks. 1 Imagine you are sitting at your desk trying to get some work done (task A). Someone knocks on your door and you let them in and start talking to them (task B). While talking, the phone rings and you answer it and talk to the person who called (task C). You finish the phone conversation and go back to the person in your office (B). Then the phone rings again (D). You answer it and deal with this new task (D), then you finish dealing with the person in your office (B), and then return to your deskjob (A). We will see more examples of such operation stacks (refered to as call stacks i.e. calling a method) a bit later in the course. For now, lets just work with data stacks of data. Example 1 Here we make a stack of strings. We assume the stack is empty initially, and then we have a sequence of pushes and pops. push(3) push(fred) push(blue) push(hello) pop() push(green) pop() pop() The elements that are popped will be hello , green , blue in that order, and afterwards the stack will have two elements in it ( fred and 3 , with fred being on top of the stack)....
View Full Document
- Spring '08
- Computer Science