java使用链栈实现数制转换

java实现链栈在前面有所介绍:http://www.cnblogs.com/lixiaolun/p/4644141.html

 

将前面java实现链栈的代码稍作修改:

package linkedstack;



public class LinkStack {

	

	private Element base;

	private Element top;

	

	class Element

	{

		public Object data;

		public Element next;

	}

	

	/**

	 * 初始化栈

	 * */

	public void initStack()

	{

		top = new Element();

		base = new Element();

		top.data=null;

		top.next=base;

		base.data=null;

		base.next=null;

	}

	

	/**

	 * 入栈

	 * */

	public void push(Object o)

	{

		Element e = new Element();

		e.data = o;

		if(top.next==base)//第一次入栈操作

		{

			e.next=base;

			top.next=e;

		}else

		{

			e.next=top.next;

			top.next=e;

		}

		

	}

	

	/**

	 * 出栈

	 * */

	public Object pop()

	{

		Object o = null;

		if(top.next==base)

		{

			System.out.println("栈中没有元素!");

			return o;

		}else

		{

			o = top.next.data;

			//System.out.println("出栈操作"+o);

			top.next=top.next.next;

		}

		return o;

	}

	/**

	 * 判断栈是否为空

	 * */

	public Boolean isEmpty()

	{

		if(top.next==base)

		{

			return true;

		}

		return false;

	}

	/**

	 * 打印栈

	 * */

	public void print()

	{

		System.out.print("打印栈:");

		Element temp =top;

		while(temp.next!=base)

		{

			System.out.print(temp.next.data+"\t");

			temp =temp.next;

		}

		System.out.println();

	}

}

  

java实现数制转换的类的代码:

package stackapplication;



import linkedstack.LinkStack;



public class Conversion {

	

	public static void main(String[] args) {

		LinkStack lStack = new LinkStack();

		lStack.initStack();

		int N = 100;//原始十进制数

		int X = 2;//要转化成X进制数

		while(N!=0)

		{

			lStack.push(N%X);

			N=N/X;

		}

		while(!lStack.isEmpty())

		{

			System.out.print(lStack.pop());

		}

		

	}

}

  

你可能感兴趣的:(java)