制作一个java应用程序,模拟实现堆栈的数据读写

堆栈的ArrayList实现

Java code
 
   
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> import java.util. * ; public class Stack{ private ArrayList pool = new ArrayList(); public Stack(){ } public Stack( int n){ pool.ensureCapacity(n); } public void clear(){ pool.clear(); } public boolean isEmpty(){ return pool.isEmpty(); } public Object pop(){ if (isEmpty()) throw new EmptyStackException(); return pool.remove(pool.size() - 1 ); } public void push(Object el){ pool.add(el); } public String toString(){ return pool.toString(); } } // end clss Stack


堆栈的链表实现
Java code
import java.util.LinkedList;
import java.util.EmptyStackException;

public class LIStack{
	private LinkedList list=new LinkedList();
	
	public LIStack(){
	}
	
	public void clear(){
		list.clear();
	}
	
	public boolean isEmpty(){
		return list.isEmpty();
	}
	
	public Object topEl(){
		if(isEmpty())
			throw new EmptyStackException();
		return list.getLast();
	}
	
	public Object pop(){
		if(isEmpty())
			throw new EmptyStackException();
		return list.removeLast();
	}
	
	public void push(Object el){
		list.addLast(el);
	}
	
	public String toString(){
		return list.toString();
	}
}//end class LIStack



堆栈的纯数组实现(只支持int类型数据,有待完善......)
Java code
 
   
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> /* *使用纯数组实现堆栈 */ public class ARStack{ private int [] a; private int MaxSize,nElem; public ARStack(){ MaxSize = 100 ; a = new int [MaxSize]; nElem = 0 ; } public void clear(){ nElem = 0 ; } public boolean isEmpty(){ return nElem == 0 ; } public int pop(){ return a[ -- nElem]; } public void push( int value){ a[nElem] = value; nElem ++ ; } public static void main(String[] args){ ARStack ar = new ARStack(); for ( int i = 10 ;i >= 0 ;i -- ){ ar.push(i); } while ( ! ar.isEmpty()){ System.out.println(ar.pop()); } } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值