JAva実装シーケンススタック

1946 ワード

シーケンススタッククラスのコード:
package sequencestack;



public class SequenceStack {

	

	private int STACK_INIT_SIZE = 5;// 

	private int INCREMENT =1;// 

	

	

	private Object []Stack = null;

	private int base;

	private int top;

	private int stacksize;

	

	/**

	 *  

	 * */

	void initStack()

	{

		Stack = new Object[STACK_INIT_SIZE];

		base=0;

		top=0;

		stacksize=0;

	}

	

	/**

	 *  

	 * */

	void push(Object o)

	{

		if(top-base>=STACK_INIT_SIZE)

		{

			System.out.println(" ");

			STACK_INIT_SIZE=STACK_INIT_SIZE+INCREMENT;

			Object []temp = new Object[STACK_INIT_SIZE];

			for(int i=0;i<stacksize;i++)

			{

				temp[i]=Stack[i];

			}

			Stack=null;

			Stack=temp;

		}

		Stack[stacksize] = o;

		stacksize++;

		top++;

	}

	/**

	 *  

	 * */

	Object pop()

	{

		Object o = null;

		if(top==base)

		{

			System.out.println(" ! null");

		}else

		{

			o=Stack[--top];

			stacksize--;

		}

		return o;

	}

	

	/**

	 *  

	 * */

	Object getTop()

	{

		Object o = null;

		if(top==base)

		{

			System.out.println(" ! null");

		}else

		{

			o=Stack[top-1];

		}

		return o;

	}

	

	/**

	 *  

	 * */

	void print()

	{

		System.out.print(" :");

		for(int i=0;i<stacksize;i++)

		{

			System.out.print(Stack[i]+"\t");

		}

		System.out.println();

	}

}


シーケンススタックテストコード:
package sequencestack;



public class SequenceStackMain {



	public static void main(String[] args) {

		SequenceStack sStack = new SequenceStack();

		sStack.initStack();

		sStack.pop();

		sStack.push(1);

		sStack.push(2);

		sStack.push(3);

		sStack.push(4);

		sStack.push(5);

		sStack.push(6);

		sStack.push(3);

		sStack.print();

		

		sStack.pop();

		sStack.pop();

		sStack.pop();

		sStack.pop();

		sStack.print();

		

		System.out.println(" :"+sStack.getTop());

		sStack.print();

	}



}