1栈的数组实现
public class ArrayStack
{
Object[] stack = null;
private int size;
void initStack(){
if(stack==null){
stack = new Object[10];
size = 0;
}
}
//判断栈是否为空,栈的起始位置为1
boolean isEmpty(){
if(size <= 0)
return true;
else
return false;
}
//进行入栈操作
T push(T obj){
ensureCapacity(size+1);
stack[++size] = obj;
return obj;
}
//进行出栈
T pop(){
if(size>=0){
return (T) stack[size--];
}
return null;
}
//确认栈的客容量大小,如果超过栈的客容量则扩充,固定的扩充大小为10
private void ensureCapacity(int len){
if(len>=this.stack.length){
System.out.println("容量太小,现在扩充");
stack = Arrays.copyOf(stack, stack.length+10);
System.out.println("现在栈的可容量大小为:"+stack.length);
}
}
public static void main(String[] args) {
ArrayStack
stack = new ArrayStack
();
stack.initStack();
System.out.println(stack.stack.length);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
stack.push(11);
stack.push(12);
stack.push(13);
stack.push(14);
stack.push(15);
stack.push(16);
stack.push(17);
stack.push(18);
stack.push(19);
stack.push(20);
stack.push(21);
stack.push(22);
stack.push(23);
stack.push(24);
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}
2栈的链表实现
public class LinkStack
{
Node
top;
public LinkStack() {
// TODO Auto-generated constructor stub
top = null;
}
void push(T data){
Node
newNode = new Node
(data);
newNode.next = top;
top = newNode;
}
T pop(){
if(!isEmpty()){
Node
popData = top; top = top.next; return popData.data; }else{ return null; } } boolean isEmpty(){ if(top==null){ return true; }else return false; } public static void main(String[] args) { LinkStack
stack = new LinkStack
(); stack.push(1); stack.push(11); stack.push(111); stack.push(1111); stack.push(11111); stack.push(111111); stack.push(1111111); stack.push(11111111); while(!stack.isEmpty()){ System.out.println(stack.pop()); } } } class Node
{ E data; Node
next = null; public Node() { } Node(E data){ this.data = data; } }