Stack, Queue, DEQueue

Interfaces

public interface Stack extends Iterable {
void push(String element);
String pop();
String peek();
int size();
}
public interface Queue extends Iterable {
void add(String element);
String poll();
String peek();
int size();
}
public interface Deque extends Queue, Stack {
void addFirst(String element);
void addLast(String element);
String pollFirst();
String pollLast();
String peekFirst();
String peekLast();
}

Implementierung

Wrapper Implementierung (Nutz Double Ended Queue DEQueue)

public class SQueue {
private final DEQueue q = new DEQueue();public void add(String e) { q.addLast(e); } //Stack wird auf der "last" Seite aufgebaut
public String poll() { return q.pollFirst(); }
public String peek() { return q.peekFirst(); }
public int size() { return q.size(); }
}
public class SStack {
private final DEQueue s = new DEQueue ();
public void push(String e) { s.addFirst(e); } //Queue auf "first" Seite
public String pop() { return s.pollFirst(); }
public String peek() { return s.peekFirst(); }
}

(Implementierung zu kompliziert - nicht nützlich)

public class DEQueue {
private int mask = 7;
private String[] es = new String[8];
private int head , tail;
public void addFirst(String e) {
es[head = (head - 1) & mask] = e;
if (tail == head) { doubleCapacity(); }
}public String pollFirst() {
String result = es[head];
es[head] = null;
if (tail != head) { head = (head + 1) & mask; }
return result;
}public String peekFirst() {
return es[head];
}public void addLast(String e) {
es[tail] = e;
tail = (tail + 1) & mask;
if (tail == head) { doubleCapacity (); }
}public String pollLast() {
if (tail != head) { tail = (tail - 1) & mask; }
String result = es[tail ];
es[tail] = null;
return result ;
}public String peekLast() {
return es [(tail - 1) & mask ];
}
public int size() { return (tail - head) & mask; }
private void doubleCapacity() {
mask = mask * 2 + 1
String[] newes = new String [mask + 1];
int i = 0, j = 0;
while (i < head) { newes [j++] = es[i++]; }
j = head += es.length;
while (i < es.length ) { newes[j++] = es[i ++]; }
es = newes ;
}
}

Java Library

java.util enthält

ArrayDeque<...> , mit addFirst und addLast

LinkedList<...>

Stack<...> , gilt als ineffizient, wird nicht mehr eingesetzt