数组实现
import java.util.NoSuchElementException;
/**
* @author 许湘扬
* @email 547139255@qq.com
* @detail 数组栈(自动扩容)
*/
public class MyArrayStack<T>
{
private static final int DEAFAULT_CAPACITY=2;
private T[] theStack;
private int theSize;
public boolean isEmpty()
{
return theSize==0;
}
public void celar()
{
theSize=0;
ensureCapacity(DEAFAULT_CAPACITY);
}
public int size()
{
return theSize;
}
public MyArrayStack()
{
theSize=0;
ensureCapacity(DEAFAULT_CAPACITY);
}
private void ensureCapacity(int newCapacity)
{
if(newCapacity<theSize)
return;
T[] oldItems=theStack;
theStack=(T[])new Object[newCapacity];
for (int i = 0; i <theSize; i++)
theStack[i]=oldItems[i];
}
public void push(T x)
{
if (theSize==theStack.length)
ensureCapacity(theSize*2+1);
theStack[theSize++]=x;
}
public T pop()
{
if (theSize==0)
throw new NoSuchElementException();
theSize--;
return theStack[size()];
}
public T top()
{
if (theSize==0)
throw new NoSuchElementException();
return theStack[size()-1];
}
public static void main(String[] args) {
MyArrayStack<Integer> stack=new MyArrayStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();
stack.push(10000);
while(!stack.isEmpty())
{
System.out.println(stack.pop());
}
System.out.println(stack.isEmpty());
}
}
/**
* @author 许湘扬
* @email 547139255@qq.com
* @detail 单向链表栈
*/
public class MyLinkedStack<T>
{
private int theSize;
private Node<T> top;
private void doClear()
{
top=null;
theSize=0;
}
public MyLinkedStack() {
doClear();
}
public int size()
{
return theSize;
}
public boolean isEmpty()
{
return top==null;
}
public void push(T x)
{
Node<T> newNode=new Node<T>(x, top);
top=newNode;
theSize++;
}
public T pop()
{
if (isEmpty())
throw new IndexOutOfBoundsException("stack is empty");
T topData=top.data;
top=top.next;
theSize--;
return topData;
}
public T top()
{
if (isEmpty())
throw new RuntimeException("stack is empty");
return top.data;
}
private static class Node<T>
{
T data;
Node<T> next;
public Node(T data, Node<T> next) {
super();
this.data = data;
this.next = next;
}
}
public static void main(String[] args)
{
MyLinkedStack<Integer> stack=new MyLinkedStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();
stack.push(10000);
while(!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
}