是一种线性的数据结构,只能在其一端添加数据和移除数据。习惯来说,这一端称之为栈顶,另一端不能操作数据的称之为栈底。特点是先进后出。
简单接口
- public interface Stack
{ - /**
- * 压入元素
- */
- boolean push(E value);
-
- /**
- * 弹出元素
- */
- E pop();
-
- /**
- * 返回栈顶元素但不移除
- */
- E peek();
-
- /**
- * 判断是否为空
- */
- boolean isEmpty();
-
- /**
- * 判断是否栈满
- */
- boolean isFull();
- }
- public class LinkedListStack
implements Stack, Iterable { -
- private Node
sentinel = new Node<>(null, null); - private int size = 0;
- private int capacity = 8;
-
- public LinkedListStack(int capacity) {
- this.capacity = capacity;
- }
-
- private static class Node
{ - Node
next; - E value;
-
- public Node(Node
next, E value) { - this.next = next;
- this.value = value;
- }
- }
-
- @Override
- public boolean push(E value) {
- if (isFull()) {
- return false;
- }
- sentinel.next = new Node<>(sentinel.next, value);
- size++;
- return true;
- }
-
- @Override
- public E pop() {
- if (isEmpty()) {
- return null;
- }
- Node
node = sentinel.next; - sentinel.next = node.next;
- size--;
- return node.value;
- }
-
- @Override
- public E peek() {
- if (isEmpty()) {
- return null;
- }
- return sentinel.next.value;
- }
-
- @Override
- public boolean isEmpty() {
- return size == 0;
- }
-
- @Override
- public boolean isFull() {
- return size == capacity;
- }
-
- @Override
- public Iterator
iterator() { - return new Iterator
() { - Node
p = sentinel.next; -
- @Override
- public boolean hasNext() {
- return p != null;
- }
-
- @Override
- public E next() {
- E value = p.value;
- p = p.next;
- return value;
- }
- };
- }
- }
- public class ArrayStack
implements Stack, Iterable { - private int capacity = 8;
- private E[] array;
- private int top = 0;
-
- @SuppressWarnings("all")
- public ArrayStack(int capacity) {
- this.capacity = capacity;
- array = (E[]) new Object[capacity];
- }
-
- @Override
- public boolean push(E value) {
- if (isFull()) {
- return false;
- }
- array[top++] = value;
- return true;
- }
-
- @Override
- public E pop() {
- if (isEmpty()) {
- return null;
- }
- return array[--top];
- }
-
- @Override
- public E peek() {
- if (isEmpty()) {
- return null;
- }
- return array[top-1];
- }
-
- @Override
- public boolean isEmpty() {
- return top == 0;
- }
-
- @Override
- public boolean isFull() {
- return top == capacity;
- }
-
- @Override
- public Iterator
iterator() { - return new Iterator
() { - int current = top;
- @Override
- public boolean hasNext() {
- return current!=0;
- }
-
- @Override
- public E next() {
- return array[--current];
- }
- };
- }
- }