スタック----動的スタックデモアルゴリズム

2465 ワード

/**
 *        
 */
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("
"); } } 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; }