栈----动态栈演示算法

/**
 * 动态栈演示代码
 */
package com.szy.structure.stack;

import java.util.Scanner;

public class DynamicStack {
	private Node TOP;
	
	DynamicStack(){
		TOP=null;
	}
	/**
	 * 判断栈是否为空
	 * @return
	 */
	public boolean isEmpty(){
		if(null==TOP){
			return true;
		}
		return false;
	}
	/**
	 * 压栈
	 * @param info
	 */
	public void push(int info) {
		Node newNode=new Node();
		newNode.info=info;
		newNode.next=TOP;
		TOP=newNode;
		System.out.println(info+" 被压入栈中");
	}
	/**
	 * 出栈
	 */
	public void pop() {
		System.out.println(TOP.info+" 出栈成功");
		TOP=TOP.next;
	}
	/**
	 * 输出栈中信息
	 */
	public void display() {
		if (isEmpty()) {
			System.out.println("空栈");
		}
		else {
			System.out.println("栈中信息:");
			for (Node temp=TOP;temp!=null;temp=temp.next) {
				System.out.println(temp.info+"  ");
			}
			System.out.println("\n");
		}
	}
	
	public static void main(String[] args) throws Exception{
		DynamicStack stack=new DynamicStack();
		int choice=0;
		while(true)
		{
			System.out.println("---MENU---");
			System.out.println("1.Push");
			System.out.println("2.Pop");
			System.out.println("3.Display");
			System.out.println("4.Exit");
			System.out.println("----------");
			System.out.println("请选择:");
			Scanner scanner=new Scanner(System.in);
			choice=scanner.nextInt();
			switch (choice) {
			case 1:
			{
				System.out.println("请输入数字:");
				int input=scanner.nextInt();
				stack.push(input);
			}
				break;
			case 2:
			{
				if (stack.isEmpty()) {
					System.out.println("空栈!");
					break;
				}
				stack.pop();
			}
			break;
			case 3:
			{
				stack.display();
			}
			break;
			case 4:
				return;
			default:
				System.err.println("无效的输入!");
				break;
			}
		}
	}
}

//声明节点
class Node{
	public int info;
	public Node next;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值