Java Stack
数组实现:
/**
* Java Stack array implements
* @param <E>
*/
public class StackX<E> {
private int mSize = 10;
private int top = -1;
private E[] stacks;
public StackX (){
stacks = (E[]) new Object[mSize];
}
public StackX(int size) {
mSize = size;
stacks = (E[]) new Object[mSize];
}
/**
* push stack
* @param e
*/
public void push (E e) {
if (top >= mSize-1) throw new RuntimeException("stack is full.");
top ++;
stacks[top] = e;
}
/**
* pop stack
* @return
*/
public E pop () {
return stacks[top--];
}
/**
* check stack
* @return
*/
public E peek () {
if (top < 0 ) throw new RuntimeException("stack is empty, error.");
return stacks[top];
}
public int size () {
return top + 1;
}
}
链表结构实现:
/**
* link implement stack
* @param <E>
*/
public class LinkStack<E> {
private Node top;
private int size;
/**
* push stack
* @param e
*/
public void push (E e) {
if (top == null) {
top = new Node(e);
} else {
Node temp = new Node(e);
temp.next = top;
top = temp;
}
size ++;
}
/**
* pop top stack element
* @return
*/
public E pop () {
if (top == null) throw new IllegalStateException("the stack is empty, error.");
Node temp = top;
top = top.next;
size --;
return temp.getElement();
}
/**
* check top stack element
* @return
*/
public E peek () {
if (top == null) throw new IllegalStateException("the stack is empty, error.");
return top.getElement();
}
public int getSize (){
return size;
}
class Node {
E e;
Node next;
public Node(E e) {
this.e = e;
}
public E getElement () {
return e;
}
}
}