Advertisement
realever15

10302期末考04

Jun 23rd, 2015
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package 期末考10302第四題;
  2. import java.util.Scanner;
  3.  
  4. public class stack {
  5.    
  6.     private int top = 0;
  7.     private int[] stackArray;
  8.    
  9.     public stack()
  10.     {
  11.         this.stackArray = new int[10];
  12.     }
  13.    
  14.     public stack(int size)
  15.     {
  16.         this.stackArray = new int[size];
  17.     }
  18.    
  19.     public void push(int a)
  20.     {
  21.         if(this.top==this.stackArray.length)
  22.         {
  23.             System.out.println("堆疊已滿, 無法存入"+a);
  24.         }
  25.         else
  26.         {
  27.             this.stackArray[top]=a;
  28.             this.top++;
  29.         }
  30.     }
  31.    
  32.     public int pop()
  33.     {
  34.         int backvalue = this.stackArray[top];
  35.         this.top--;
  36.         return backvalue;
  37.     }
  38.    
  39.     public void popAll()
  40.     {
  41.         for(int i=this.top-1;i>=0;i--)
  42.         {
  43.             System.out.print(this.stackArray[i]+" ");
  44.             this.stackArray[i]=0;
  45.         }
  46.     }
  47.    
  48.     public static void main(String[] args) {
  49.         System.out.print("請輸入欲放入堆疊的值(輸入-99 表示結束):");
  50.         Scanner scn =new Scanner(System.in);
  51.         stack stack=new stack(5);
  52.         while(true)
  53.         {
  54.             int n=scn.nextInt();
  55.             if(n==-99)
  56.             {
  57.                 break;
  58.             }
  59.             stack.push(n);
  60.         }
  61.         System.out.print("輸出的堆疊值依序為:");
  62.         stack.popAll();
  63.         scn.close();
  64.  
  65.     }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement