public class StackList<E> implements Stack<E>{
//指向栈顶元素
protected Node top;
//栈中元素的数目
protected int size;
public StackList() {
this.size=0;
this.top=null;
}
@Override
public void push(E e) {
//创建一个新节点,将其作为首节点插入
//Node<E> node = new Node<>(e,top);
//更新首节点引用
//top = node;
top = new Node<>(e,top);
//更新操作长度
size ++;
}
@Override
public E pop() throws ExceptionStackEmpty {
if (isEmpty()){
throw new ExceptionStackEmpty("意外:栈空");
}
//获取当前的节点
E elem = (E) top.getElem();
//重置首节点元素
top = top.getNext();
//操作长度减一
size--;
return elem;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return top == null;
}
@Override
public E top() throws ExceptionStackEmpty {
if (isEmpty()){
throw new ExceptionStackEmpty("意外:栈空");
}
return (E) top.getElem();
}
}
public class LinkedQueue<E> implements Queue<E>{
//指向表首元素
protected Node<E> head;
//指向表末元素
protected Node<E> tail;
//队列中元素的数目
protected int size;
public LinkedQueue() {
//构造方法(空队列)
head = tail = null;
size = 0;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
// return (head = tail) == null;
return 0 == size;
}
@Override
public E front() throws ExceptionQueueEmpty {
return head.getElem();
}
@Override
public void enqueue(E e) throws ExceptionQueueFull {
Node<E> node = new Node<>();
node.setElem(e);
node.setNext(null);
if (0 == size){
//若此前队列为空,则直接插入
head = node;
}else {
tail.setNext(node);
}
//更新指向末节点引用
tail = node;
//更新规模
size++;
}
@Override
public E dequeue() throws ExceptionQueueEmpty {
if(isEmpty()){
throw new ExceptionQueueEmpty("意外:队列空");
}
E old = head.getElem();
head = head.getNext();
size--;
//若队列已空,须将末节点引用置空
if (0 == size){
tail = null;
}
return old;
}
}