数据结构-单链表实现栈

package 数据结构;

public class Link
{
	public int data ;
	public  Link next ;//记录下一个节点
	
	public Link ( int data )
	{
		this.data = data ;
	}
}
package 数据结构;

public class LinkStack
{
	private Link top ;//栈顶
	
	//入栈
	public void push ( int data )
	{
		Link newLink = new Link ( data ) ;
		
		// 如果为空 , 直接将新节点变为栈顶
		if ( isEmpty () )
		{
			top = newLink ;
			return ;//退出
		}
		//不为空,将新节点的next指向原栈顶
		newLink.next = top ;
		//新节点成为栈顶
		top = newLink ;
	}
	
	//出栈
	public Link pop ()
	{
		if ( isEmpty () )
		{
			System.out.println ( "当前栈中没有元素" );
			return null;
		}
		
		Link temp = top ;//存放要出栈的节点
		
		top = top.next ;//栈顶元素变为原栈顶的next
		return temp ;
	}
	
	//判断是否为空
	public boolean isEmpty ()
	{
		return top == null ;
	}
	
	//遍历
	public void display ()
	{
		if ( isEmpty () )
		{
			System.out.println ( "栈为空" );
			return ;
		}
		
		Link current = top ;//记录遍历到哪儿
		
		while ( current != null )
		{
			System.out.print ( current.data + " " );
			current = current.next ;
		}
		System.out.println ();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值