Stack和Queue本质上都是一个装东西的list,区别就在于它们insert(push)和remove(pop)的方式不同。
如果我们把push和pop看作吃东西和拉屎,那stack就是一个有口无肛门的生物,它的吃和拉都要从最顶上拿出来。
push and pop code for Stack:
public void push(E element) {
if ( top != stack.length - 1 ) {
stack[++top] = element;
}
}
public E pop() throws ArrayIndexOutOfBoundsException {
if ( isEmpty() ) { throw new ArrayIndexOutOfBoundsException("Stack is empty"); }
else {return stack[top--]; }
}
如果我们运行一下code
Stack<Integer> Stack = new Stack<>(3);
Stack.push(1);
Stack.push(2);
Stack.push(3);
我们得到的stack就是这样的:
1,2,3
之后我们输入:
Stack.pop();
Stack就会变成: 1,2
也就是说它的加入和拿出都是从peek拿出去的。就好像做蛋糕,你想把两层的蛋糕变成三层的,你会把新的蛋糕胚直接盖到顶上。吃蛋糕也一样,是从顶上开始往下吃。
Queue和Stack比起来就是一个有口有肛门的哺乳动物,它的push和Stack一样都是往顶上放,但是pop则是从最底部拿。
pop and push code for Queue:
public void push(E element) {
if ( back != queue.length ) {
queue[back++] = element;
}
}
public E pop() throws ArrayIndexOutOfBoundsException {
if ( isEmpty() ) { throw new ArrayIndexOutOfBoundsException("Queue is empty"); }
else {
E poppedElement = queue[0];
for (int s = 1; s <= back - 1; s++) {
queue[s - 1] = queue[s];
}
back -= 1;
return poppedElement;
}
}
如果我们运行一下code
Queue<Integer> Queue = new Queue<>(3);
Queue.push(1);
Queue.push(2);
Queue.push(3);
我们得到的Queue就是这样的(和Stack一样):
1,2,3
之后我们输入:
Queue.pop();
我们就会得到Queue:2,3