// 数组组成的栈
package com.stack;
public class ArrayStack{
private int top;
private int[] array;
private int capcity;
public ArrayStack(int capcity){
this.array = new int[capcity];
this.top = -1;
this.capcity = capcity;
}
public void push(int data){
if(isFull()){
throw new RuntimeException("stack is Full");
}
array[++top] = data;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("stack is Empty");
}
return array[top --];
}
public int peek(){
if(isEmpty()){
throw new RuntimeException("stack is Empty");
}
return array[top];
}
public void clear(){
top = -1;
}
public int size(){
return top + 1;
}
public boolean isFull(){
return (top + 1) == capcity;
}
public boolean isEmpty(){
return top == -1;
}
}
// 链表组成的栈
package com.stack;
import java.util.LinkedList;
public class LinkStack<T> {
private LinkedList<T> linkStack;
public LinkStack() {
linkStack = new LinkedList<T>();
}
public void push(T item){
linkStack.addFirst(item);
}
public T pop(){
if(linkStack.isEmpty()){
throw new RuntimeException("stack is null");
}
return linkStack.removeFirst();
}
public T peek(){
if(linkStack.isEmpty()){
throw new RuntimeException("stack is null");
}
return linkStack.getFirst();
}
public int size(){
return linkStack.size();
}
}