Java实现--链表栈

 用链表实现栈:

其实就只是换了个名字,包装起来而已,没什么新的东西。

注:这里插入结点的方法应为在头部插入结点(与输入的值逆置),这样构成的才是栈

关于定义链表可以查看我的另一篇博文https://blog.csdn.net/szlg510027010/article/details/82862965

/**
 * 用链表实现栈
 * @author Administrator
 *
 */
public class LinkStack {
	private LinkList theList;
	
	public LinkStack(){
		theList = new LinkList(); 
	}
	
	//入栈
	public void push(int data) {
		theList.Insert(data);
	}
	
	//出栈
	public int pop(){
		return theList.delete().data;
	}
	
	//检查栈是否为空
	public boolean isEmpty() {
		return theList.isEmpty();
	}
	
	public void displayStack() {
		System.out.print("Stack (top--->bottom): ");
		theList.displayList();
	}
}
/**
 * 测试(链表)栈
 * @author Administrator
 *
 */
public class TestLinkStack {
	public static void main(String[] args) {
		LinkStack theStack = new LinkStack();
		theStack.push(20);
		theStack.push(40);
		
		theStack.displayStack();
		
		theStack.push(60);
		theStack.push(80);
		
		theStack.displayStack();
		
		theStack.pop();
		theStack.pop();
		
		theStack.displayStack();
	}
}

测试结果:

Stack (top--->bottom): {40} {20} 
Stack (top--->bottom): {80} {60} {40} {20} 
Stack (top--->bottom): {40} {20} 
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值