
Assuming a char array stack,
+---+ +---+ +---+ +---+ +---+
| | 2 | | 2 | | 2 | | 2 | |
+---+ +---+ +---+ +---+ +---+
| | 1 | | 1 top->| B | 1 top->| B | 1 | B | 1
+---+ +---+ +---+ +---+ +---+
| | 0 top->| A | 0 | A | 0 | A | 0 top->| A | 0
+---+ +---+ +---+ +---+ +---+
top->
initial push 'A' push 'B' top pop
RETURNED 'B'
| Infix | Prefix | Postfix |
| 3 + 5 | (+ 3 4) | 3 4 + |
| 3 + (4 * 5) | (+ 3 (* 4 5)) | 3 4 5 * + |
| (3 + 4) * 5 | (* (+ 3 4) 5) | 3 4 + 5 * |
public class Stack<Item> {
private int N; // size of the stack
private Node first; // top of stack
// helper linked list class
private class Node {
private Item item;
private Node next;
}
public Stack() { first = null; N = 0; }
public boolean isEmpty() { return first == null; }
public int size() { return N; }
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
N--;
return item; // return the saved item
}
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}
}
Assuming a char queue, (F for front, B for back)
initial +---+---+---+---+-
empty | | | | |
queue +---+---+---+---+-
^ ^
| |
B F
+---+---+---+---+-
enqueue 'p' | p | | | |
+---+---+---+---+-
^ ^
| |
B F
+---+---+---+---+-
enqueue 'd' | p | d | | |
+---+---+---+---+-
^ ^
| |
F B
+---+---+---+---+-
dequeue | p | d | | |
+---+---+---+---+-
^ ^
| |
F B
+---+---+---+---+-
enqueue 'c' | p | d | c | |
+---+---+---+---+-
^ ^
| |
F B
public class Queue<Item> {
private int N; // number of elements on queue
private Node first; // beginning of queue
private Node last; // end of queue
// helper linked list class
private class Node {
private Item item;
private Node next;
}
public Queue() { first = null; last = null; N = 0; }
public boolean isEmpty() { return first == null; }
public int size() { return N; }
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
}
public void enqueue(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
public Item dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
Item item = first.item;
first = first.next;
N--;
if (isEmpty()) last = null; // to avoid loitering
return item;
}
}