1.线性栈
class LinearStack{
public int[] array;
public int size;
public LinearStack(){
this(10);
}
public LinearStack(int capias){
array=new int[capias];
size=0;
}
public void push(int e){
if(size==array.length){
resize(array.length*2);
}
array[size]=e;
size++;
}
public int pop(){
if(size==0){
System.out.println("栈为空!");
return -1;
}
int e=array[size-1];
size--;
if(size==array.length/4&&array.length>10){
resize(array.length/2);
}
return e;
}
public int peek(){
return array[size-1];
}
public int size(){
return size;
}
public void clear(){
array=new int[10];
size=0;
}
public void print(){
if(size==0){
System.out.println("bottom[]top "+size+"/"+array.length);
}else {
String s="bottom[";
for(int i=0;i<size;i++){
if(i==size-1){
s+=array[i]+"]top "+size+"/"+array.length;
}else {
s+=array[i]+",";
}
}
System.out.println(s);
}
}
public void resize(int capias){
int[] newArray=new int[capias];
for(int i=0;i<Math.min(array.length,newArray.length);i++){
newArray[i]=array[i];
}
array=newArray;
}
}
2.链栈
class ChainStack{
private int size;
Node head;
public ChainStack(){
this.size=0;
this.head=new Node();
}
public ChainStack(int[] array){
this();
for(int i=0;i<array.length;i++){
push(array[i]);
}
}
public void push(int e){
head.next=new Node(e,head.next);
size++;
}
public int pop(){
if(size==0&&head.next==null){
System.out.println("当前栈为空!");
return -1;
}else{
Node p;
p=head.next;
int e=p.e;
head.next=p.next;
p=null;
size--;
return e;
}
}
public int peek(){
return head.next.e;
}
public int size(){
return size;
}
public void clear(){
head=null;
size=0;
}
public void print(){
if(size==0){
System.out.println("top[]bottom "+size);
}else{
String s="top[";
Node p=head.next;
while(true){
if(p.next==null){
s+=p.e+"]bottom "+size;
break;
}else{
s+=p.e+",";
p=p.next;
}
}
System.out.println(s);
}
}
private class Node{
int e;
Node next;
public Node(){
this.e=0;
this.next=null;
}
public Node(int e,Node next){
this.e=e;
this.next=next;
}
}
}