是一种支持push,pop,enqueue操作的数据类型。push和pop都是对队列同一端的操作,enqueue和push对应,但是操作的是队列的另一端
和栈的思想基本一致,但是多维护一个指向栈底(也就是链表尾部)的指针,方便进行enqueue操作
public class Steque <Item>{
private class StequeNode {
Item item;
StequeNode next;
}
private StequeNode first;
private StequeNode last;
private int N;
private boolean isEmpty(){
return first == null;
}
private int size() {
return N;
}
private StequeNode newNode(Item item) {
StequeNode temp = new StequeNode();
temp.item = item;
return temp;
}
public void push(Item item) {
StequeNode xNode = newNode(item);
if(isEmpty()) {
first = xNode;
last = xNode;
}else {
xNode.next = first;
first = xNode;
}
N++;
}
public Item pop() {
if(isEmpty()){
System.out.println("栈已空");
return null;
}
StequeNode temp = first;
if(size() == 1) {
first = null;
last = null;
}else {
first = first.next;
temp.next = null;
}
N--;
return temp.item;
}
public void enqueue(Item item) {
StequeNode xNode = newNode(item);
if(isEmpty()) {
first = xNode;
last = xNode;
}else {
last.next = xNode;
last = xNode;
}
N++;
}
public void printStack() {
StequeNode temp = first;
while(temp != null) {
System.out.println(temp.item);
temp = temp.next;
}
}
}