Stacks 1
Stacks 1
s
Item remove order:
Last In, First Out
Item add order: A top
s.push(“A”);
s
Item remove order:
Last In, First Out
Item add order: A, B top
s.push(“A”);
s.push(“B”);
s
Item remove order:
Last In, First Out
Item add order: A, B, C top
s.push(“A”);
s.push(“B”);
s.push(“C”); C
s
Item remove order:
Last In, First Out
Item add order: A, B, C top
s.push(“A”);
s.push(“B”);
s.push(“C”);
s.pop(); B
s
Item remove order: C
Last In, First Out
Item add order: A, B, C top
s.push(“A”);
s.push(“B”);
s.push(“C”);
s.pop();
s.pop(); A
s
Item remove order: C, B
Last In, First Out
Item add order: A, B, C top
s.push(“A”);
s.push(“B”);
s.push(“C”);
s.pop();
s.pop();
s.pop();
s
Item remove order: C, B, A
A Stack Interface
public interface Stackable<anyType>
{
public void push(anyType x); //add x to the top
while(!s.isEmpty())
System.out.println(s.pop());
Stack mechanics
MyStack<String> s = new MyStack(); top temp t2
W *
s.push(“B”);
s.push(“*”);
B
s.push(“W”);
String temp = s.pop();
String t2 = s.peek(); OUTPUT
W
s.push(t2); *
s.push(temp); *
while(!s.isEmpty())
System.out.println(s.pop());
Stack mechanics
MyStack<String> s = new MyStack(); top temp t2
W *
s.push(“B”);
s.push(“*”);
s.push(“W”);
String temp = s.pop();
String t2 = s.peek(); OUTPUT
W
s.push(t2); *
s.push(temp); *
B
while(!s.isEmpty())
System.out.println(s.pop());
Creating the MyStack
public class MyStack<anyType> implements Stackable<anyType>
{
private List<anyType> list;
public MyStack()
{
list = new ArrayList(); //could also be a Linked List
}
//now define interface methods and a toString method
}