Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package 期末考10302第四題;
- import java.util.Scanner;
- public class stack {
- private int top = 0;
- private int[] stackArray;
- public stack()
- {
- this.stackArray = new int[10];
- }
- public stack(int size)
- {
- this.stackArray = new int[size];
- }
- public void push(int a)
- {
- if(this.top==this.stackArray.length)
- {
- System.out.println("堆疊已滿, 無法存入"+a);
- }
- else
- {
- this.stackArray[top]=a;
- this.top++;
- }
- }
- public int pop()
- {
- int backvalue = this.stackArray[top];
- this.top--;
- return backvalue;
- }
- public void popAll()
- {
- for(int i=this.top-1;i>=0;i--)
- {
- System.out.print(this.stackArray[i]+" ");
- this.stackArray[i]=0;
- }
- }
- public static void main(String[] args) {
- System.out.print("請輸入欲放入堆疊的值(輸入-99 表示結束):");
- Scanner scn =new Scanner(System.in);
- stack stack=new stack(5);
- while(true)
- {
- int n=scn.nextInt();
- if(n==-99)
- {
- break;
- }
- stack.push(n);
- }
- System.out.print("輸出的堆疊值依序為:");
- stack.popAll();
- scn.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement