javaアプリケーションを作成して、スタックのデータ読みと書きをシミュレートします。

8254 ワード

スタックのArayList実現
Javaコード

   
<!-- 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コード
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 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()); } } }