Stack Interface
package com.nasuf.arraylist;
public interface Stack<T> {
boolean isEmpty();
void push(T data);
/**
* 返回栈顶元素,未出栈
* @return
*/
T peek();
/**
* 出栈,返回栈顶元素,同时从栈中移除该元素
* @return
*/
T pop();
}
Sequence Stack
package com.nasuf.arraylist;
import java.io.Serializable;
import java.util.EmptyStackException;
public class SeqStack<T> implements Stack<T>, Serializable {
private static final long serialVersionUID = 7850303094177457725L;
/**
* 栈顶元素,-1代表空栈
*/
private int top = -1;
/**
* 栈容量,默认为10
*/
private int capacity = 10;
/**
* 存放元素的数组
*/
private T[] array;
private int size;
public SeqStack(int capacity) {
array = (T[]) new Object[capacity];
}
public SeqStack() {
array = (T[]) new Object[this.capacity];
}
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return this.top == -1;
}
/**
* 添加元素,从栈顶(数组尾部)插入
* @param data
*/
@Override
public void push(T data) {
if (array.length == size)
ensureCapacity(size*2+1); //扩容
// 从栈顶添加元素
array[++top] = data;
size ++;
}
@Override
public T peek() {
if (isEmpty())
throw new EmptyStackException();
return array[top];
}
@Override
public T pop() {
if(isEmpty())
throw new EmptyStackException();
size --;
return array[top--];
}
private void ensureCapacity(int capacity) {
if (capacity < size)
return;
T[] old = array;
array = (T[]) new Object[capacity];
// 复制元素
for (int i=0; i<size; i++) {
array[i] = old[i];
}
}
}
LinkedStack
import java.io.Serializable;
import java.util.EmptyStackException;
public class LinkedStack<T> implements Stack<T>, Serializable{
private static final long serialVersionUID = -4338010259113832656L;
private static class Node<AnyType> {
public AnyType data;
public Node<AnyType> next;
public Node() {
}
public Node(AnyType d) {
data = d;
}
public Node(AnyType d, Node<AnyType> n) {
data = d;
next = n;
}
}
private Node<T> top;
private int size;
public LinkedStack() {
this.top = new Node<T> ();
}
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return top == null || top.data == null;
}
@Override
public void push(T data) {
if (data == null) {
throw new StackOverflowError();
}
if (this.top == null) {
this.top = new Node<T> (data);
} else if (this.top.data == null) {
this.top.data = data;
} else {
Node<T> p = new Node<>(data, this.top);
top = p; //更新栈顶
}
size ++;
}
@Override
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return top.data;
}
@Override
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
T data = top.data;
top = top.next;
size --;
return data;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。