帮楼主写了一个,不晓得写得符合要求不?希望对楼主有帮助: public class Stack { //栈数组 long stackArr[]; //栈的大小 int maxSize; //栈的顶部 int top; //初始化一个大小为size的栈 public Stack(int size){ maxSize = size; stackArr = new long[size]; top = -1; } //出栈操作 public long pop(){ return stackArr[top--]; } //进栈操作 public void push(long value){ stackArr[++top] = value; } //判断栈是否为空 public boolean isEmpty(){ return top == -1; } //判断栈是否已满 public boolean isFull(){ return top == maxSize-1; } //取栈顶元素 public long peek(){ return stackArr[top]; } public static void main(String[] args) { Stack stack = new Stack(10); while(!stack.isFull()){ long v = (long) (Math.random()*100); stack.push(v); System.out.print(v+" "); } System.out.println(); while(!stack.isEmpty()){ long topValue = stack.pop(); System.out.print(topValue+" "); } System.out.println(); } }
用LinkdeList实现: import java.util.*; class Stacks{//=====================================定义堆栈类
private LinkedList list=new LinkedList();
int top=-1;
public void push(Object obj){ //入栈
list.add(obj);
top++;
}
public Object pop(){ //出栈
if(top<0)return null;
Object obj=list.getLast();
list.removeLast();
top--;
return obj;
}
public Object peek(){return list.getLast();} //获得栈顶数据 public boolean isEmpty()//判空 {if(list.size()==0) return true;else return false;}
public class Stack {
//栈数组
long stackArr[];
//栈的大小
int maxSize;
//栈的顶部
int top;
//初始化一个大小为size的栈
public Stack(int size){
maxSize = size;
stackArr = new long[size];
top = -1;
}
//出栈操作
public long pop(){
return stackArr[top--];
}
//进栈操作
public void push(long value){
stackArr[++top] = value;
}
//判断栈是否为空
public boolean isEmpty(){
return top == -1;
}
//判断栈是否已满
public boolean isFull(){
return top == maxSize-1;
}
//取栈顶元素
public long peek(){
return stackArr[top];
}
public static void main(String[] args) {
Stack stack = new Stack(10);
while(!stack.isFull()){
long v = (long) (Math.random()*100);
stack.push(v);
System.out.print(v+" ");
}
System.out.println();
while(!stack.isEmpty()){
long topValue = stack.pop();
System.out.print(topValue+" ");
}
System.out.println();
}
}
import java.util.*;
class Stacks{//=====================================定义堆栈类
private LinkedList list=new LinkedList();
int top=-1;
public void push(Object obj){ //入栈
list.add(obj);
top++;
}
public Object pop(){ //出栈
if(top<0)return null;
Object obj=list.getLast();
list.removeLast();
top--;
return obj;
}
public Object peek(){return list.getLast();} //获得栈顶数据
public boolean isEmpty()//判空
{if(list.size()==0) return true;else return false;}
}