数据结构——用(单端)链表实现栈(java实现)

    栈是一种先进后出的数据结构,即只有最后插入的数据项才运行被访问,今天用单端链表模拟了栈的实现,代码如下:

/*
 *You can just get the top item in the stack,what is first inserted is in the bottom of stack!
 *
 *
*/
class Link
{
	public long dData;
	public Link next;
	public Link(long dData)
	{
		this.dData = dData;
	}
	public void displayLink()
	{
		System.out.print("{" + this.dData + "}");
	}
}

class LinkList
{
	Link first;

	public LinkList()
	{
		this.first = null;
	}

	public boolean isEmpty()
	{
		return first == null;
	}

	public void insertFirst(long key)	//this method will be used in push()
	{
		Link newLink = new Link(key);
		if(this.isEmpty())	//if list is empty
		{
			first = newLink;
			newLink.next = null;
		}
		else
		{
			newLink.next = first;
			first = newLink;
		}
	}

	public long deleteFirst()		//this method will be used in pop();
	{
		Link current = null;
		if(this.isEmpty())
		{
			System.out.println("Your stack is empty");
			return -1;
		}
		else
		{
			current = first;
			first = first.next;
			return current.dData;
		}
	}

	public void displayList()
	{
		Link current = first;
		System.out.print("stack (top-->buttom): ");
		if(this.isEmpty())
		{
			System.out.println("Your list is empty, nothing to show!");
		}
		else
		{
			while(current!=null)
			{
				current.displayLink();
				current = current.next;
			}
			System.out.println("");
		}
	}
}

class LinkStack
{
	LinkList list = new LinkList();
	public void push(long key)
	{
		list.insertFirst(key);
	}
	public long pop()
	{
		return list.deleteFirst();
	}
	public void showStack()
	{
		list.displayList();
	}
}

class LinkStackApp
{
	public static void main(String[] args)
	{
		LinkStack linkStack = new LinkStack();
		linkStack.push(20);	//push four element
		linkStack.push(40);

		linkStack.showStack();	//look at what is in the stack

		linkStack.push(60);
		linkStack.push(80);

		linkStack.showStack();	//look at what is in the stack

		linkStack.pop();
		linkStack.pop();

		linkStack.showStack();	//look at what is in the stack
	}
}

运行效果:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值