通常,栈是限定插入和删除,只能在表的“端点”进行线性表
栈是限定仅在表尾进行插入或删除的线性表,通常称其表尾为栈顶,表头为栈底。
栈为后进先出(Last In First Out)的线性表 LIFO表。
栈的实现(java version)
基于数组的实现
public class Stack<E> { private final static int initialSize = 10; private int maxSize; private Object[] data; private int top = 0; private boolean autoIncrease; public Stack() { data = new Object[initialSize]; maxSize = initialSize; autoIncrease = true; } public Stack(int initSize) { if (initSize <= 0) { throw new RuntimeException("Initial Size couldn't be smaller than zero!"); } data = new Object[initSize]; maxSize = initSize; } public boolean isEmpty() { return top <= 0; } public boolean push(E e) { if (top >= maxSize) { if (autoIncrease) { increaseSize(); } else { throw new RuntimeException("栈已满!"); } } data[top] = e; top++; return true; } public E peek() { if (top <= 0) { throw new RuntimeException("栈已空"); } return (E) data[top - 1]; } public E pop() { if (top <= 0) { throw new RuntimeException("栈已空"); } E e = (E) data[top - 1]; top--; return e; } private void increaseSize() { maxSize *= 2; Object[] newData = new Object[maxSize]; for (int i = 0; i < data.length; i++) { newData[i] = data[i]; } data = newData; } public static void main(String[] args) { Stack<Integer> list = new Stack<Integer>(); for (int i = 0; i < 20; i++) { list.push(i); } System.out.println(list.isEmpty()); while (!list.isEmpty()) { System.out.println(list.pop()); } } }
- 基于链表的实现
public class LinkedStack<E> {
private Node<E> next;
private int size=0;
private Integer maxSize;
public LinkedStack() {
super();
}
public LinkedStack(int maxSize) {
super();
this.maxSize = maxSize;
}
public boolean isEmpty() {
return size <= 0;
}
public boolean push(E e) {
if(maxSize!=null&&size>maxSize){
System.out.println("Stack is full!");
return false;
}
Node<E> node=new Node<E>();
node.setData(e);
if(next ==null){
next=node;
}else{
Node<E> tmp=next;
next=node;
node.setNext(tmp);
}
size++;
return true;
}
public E peek() {
if(size<=0){
System.out.println("Stack is Empty");
return null;
}
return (E)next.getData();
}
public E pop() {
if(size<=0){
System.out.println("Stack is Empty");
return null;
}
E backData=(E)next.getData();
Node<E> nextOne=next.getNext()==null?null:next.getNext();
next=nextOne;
size--;
return backData;
}
public static void main(String[] args) {
LinkedStack<Integer> list=new LinkedStack<Integer>();
for(int i=0;i<20;i++){
list.push(i);
}
System.out.println(list.isEmpty());
while(!list.isEmpty()){
System.out.println(list.pop());
}
}
}
public class Node<E> {
private Object data;
private Node<E> next;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
···
·
·