Date post: | 03-Jun-2018 |
Category: |
Documents |
Upload: | shefali-gupta |
View: | 225 times |
Download: | 0 times |
of 21
8/11/2019 Intro Stack
1/21
Stacks as an AbstractData Type
CS1316: Representing
Structure and Behavior
8/11/2019 Intro Stack
2/21
Story Stack: Another useful kind of list
An example of an Abstract Data Type (ADT):
We can define the methods and the behavior apartfrom any implementation. There are multiple implementations, some better
than others.
Can use a stack to reverse a list in less time,but more space.
A classic tradeoff! Space for time.
8/11/2019 Intro Stack
3/21
Key idea #1:
Introducing a Queue Last-In-First-Out List
First item in the list is the lastone out. Last one in is first one out.
I got here
first!
I got here
second!
I got here
third!
This is the top
of the stack
8/11/2019 Intro Stack
4/21
New items go at the top
I got herefirst!
I got heresecond!
I got herethird!
This is the
newtopof the
stack
I got herefourth!
8/11/2019 Intro Stack
5/21
Items onlyget removed from the
top
I got herefirst!
I got heresecond!
I got herethird!
This is the
new (er, old )
topof thestack
I got here
fourth! Andnow Im outta
here!
8/11/2019 Intro Stack
6/21
8/11/2019 Intro Stack
7/21
Example
stack
Welcome to DrJava.
> Stack stack = new Stack()
> stack.push("This")
> stack.push("is")
> stack.push("a")> stack.push("test")
> stack.size()
4
> stack.peek()
"test"
> stack.pop()"test"
> stack.pop()
"a"
> stack.pop()
"is"
> stack.pop()"This"
> stack.pop()
java.util.NoSuchElementException:
Notice anything
interesting aboutthe order in and
the order out?
8/11/2019 Intro Stack
8/21
8/11/2019 Intro Stack
9/21
Stack
methods
//// Methods ///
public void push(Object element){
// New elements go at the front
elements.addFirst(element);
}
public Object peek(){
return elements.getFirst();
}
public Object pop(){
Object toReturn = this.peek();
elements.removeFirst();
return toReturn;
}
public int size(){return elements.size();}
8/11/2019 Intro Stack
10/21
A stack is a stack,
no matter what lies beneath.
Our description of the stack minustheimplementation is an example of an abstractdata type (ADT).
An abstract type is a description of the methods that adata structure knows and what the methods do. We can actually write programs that use the
abstract data type withoutspecifying theimplementation.
There are actually manyimplementations that willwork for the given ADT. Some are better than others.
8/11/2019 Intro Stack
11/21
Building a Stack from an Array
/**
* Implementation of a stack as an array
**/
public class Stack2 {
private static int ARRAYSIZE = 20;
/** Where we'll store our elements */
private Object[] elements;
/** Index where the top of the stack is */
private int top;
8/11/2019 Intro Stack
12/21
Stack2 = array + top index
/// Constructor ////
public Stack2() {
elements = new Object[ARRAYSIZE];
top = 0;
}
8/11/2019 Intro Stack
13/21
Stack2
Methods
//// Methods ///
public void push(Object element){
// New elements go at the top
elements[top]=element;
// then add to the top
top++;
if (top==ARRAYSIZE){System.out.println("Stack overflow!");
}
}
public Object peek(){
if (top==0){
System.out.println("Stack empty!");
return null;} else{
return elements[top-1];}
}
public Object pop(){
Object toReturn = this.peek();
top--;
return toReturn;}
/** Size is simply the top index */
public int size(){return top;}
8/11/2019 Intro Stack
14/21
Testing
Stack2
Welcome to DrJava.
> Stack2 stack = new Stack2();
> stack.push("Matt")
> stack.push("Katie")
> stack.push("Jenny")
> stack.size()
3
> stack.peek()
"Jenny"
> stack.pop()"Jenny"
> stack.pop()
"Katie"
> stack.pop()
"Matt"> stack.pop()
Stack empty!
null
8/11/2019 Intro Stack
15/21
What are stacks good for?
The algorithm for converting an equationinto a tree uses a stack.
As new functions get called, position inold functions get pushed on a stack. So you always return to the last function you
were in.
If an error occurs, you get a stack trace. If your recursion goes into an infinite loop,what error do you get? Stack overflow!
8/11/2019 Intro Stack
16/21
A Stack Example: New Reverse
Recall our original implementation of reverse().
We go to the end of the original list to find the last(). We then remove() it (which involves walking the list
until we find the one before last())
We then insert it at the end of the new list (via add(),which does last().insertAfter()).
All told: For each node, we walk the whole list
three times. O(n*n2)=O(n3)
8/11/2019 Intro Stack
17/21
Original
Reverse
/**
* Reverse the list starting at this,
* and return the last element of the list.
* The last element becomes the FIRST element
* of the list, and THIS goes to null.
**/
public LLNode reverse() {
LLNode reversed, temp;
// Handle the first node outside the loop
reversed = this.last();
this.remove(reversed);
while (this.getNext() != null)
{
temp = this.last();
this.remove(temp);
reversed.add(temp);
};
// Now put the head of the old list on the end of
// the reversed list.
reversed.add(this);
// At this point, reversed
// is the head of the list
return reversed;
}
8/11/2019 Intro Stack
18/21
Testing Reverse in
SoundListTest()
public void reverseTest(){
FileChooser.setMediaPath("D:/cs1316/MediaSources/");
Sound s = null; // For copying in sounds
s = new Sound(FileChooser.getMediaPath("guzdial.wav"));
SoundNode root = new SoundNode(s);
s = new Sound(FileChooser.getMediaPath("is.wav"));SoundNode one = new SoundNode(s);
root.last().insertAfter(one);
s = new Sound(FileChooser.getMediaPath("scritch-q.wav"));
SoundNode two = new SoundNode(s);
root.last().insertAfter(two);
s = new Sound(FileChooser.getMediaPath("clap-q.wav"));
SoundNode three = new SoundNode(s);
two.insertAfter(three);
//root.playFromMeOn();
SoundNode reversed = (SoundNode) root.reverse2();
reversed.playFromMeOn();
}
8/11/2019 Intro Stack
19/21
Stack-based
Reverse
/**
* Reverse2: Push all the elements on
* the stack, then pop all the elements
* off the stack.
**/
public LLNode reverse2() {LLNode reversed, current, popped;
Stack stack = new Stack();
current=this;
while (current != null)
{ stack.push(current);
current = current.getNext();
}
reversed = (LLNode) stack.pop();
current = reversed;
while (stack.size()>0) {
popped=(LLNode) stack.pop();
current.insertAfter(popped);
current = popped;
}
return reversed;
}
8/11/2019 Intro Stack
20/21
8/11/2019 Intro Stack
21/21
Whats the diff? Space
How much spacedoes reverse2() take?
Whatever space the stack takes.
How much additional space does reverse()take? None
Very common tradeof f : Space for t ime.
You can make an algorithm go faster, by using more
space. If you need to fit into less memory, you have to domore processing, which takes more time.