简单栈管理

来源:互联网 发布:爱奇艺视频软件 编辑:程序博客网 时间:2024/05/19 23:03
/*A simple stack class for characters*/import java.util.*;//import java.io.IOException;class SimpleStack{char [] data; //this array holds the stackint tos;  //index of top of stack//construct an empty stack given its size//-------------------------------------------------------------SimpleStack(int size){data = new char[size];tos = 0;}//push a character onto the stack.//-------------------------------------------------------------void push(char ch){if (isFull()){System.out.println("---Stack is Full!");return;}data[tos]=ch;tos++;}//pop a character from the stack.char pop(){if (isEmpty()){System.out.println("---Stack is Empty!");return (char)0;}tos--;return data[tos];}//return true if the stack is empty.//-------------------------------------------------------------boolean isEmpty(){return tos==0;}//return true if the stack is full.boolean isFull(){return tos==data.length;}}//-----------------------------------------------------------------class  SimpleStackDemo{public static void main(String[] args) {int i;char ch;//---------------------------------------------------------System.out.println("Demonstrate SimpleStack\n");//constructs 10-elements on the empty stack.SimpleStack stack = new SimpleStack(10);System.out.println("Push 10 items onto a 10-element stack.");//Push the letters A through J onto the stack.System.out.println("Pushing:");for (ch='A';ch<'K' ;ch++ ){System.out.print(ch);stack.push(ch);}System.out.println("\nPop those 10 items from the stack.");//Now ,pop the characters off the stack.//Notice that order will be the reverse of those pushed.System.out.print("Poping:");for (i=0;i<10 ;i++ ){ch = stack.pop();System.out.print(ch);}//----------------------------------------------------------------------System.out.println("\n\nNext, use isEmpty() and isFull() "+"to fill and empty the stack.");//Push the letters until the stack is full.System.out.print("Pushing:");for (ch='A';!stack.isFull() ; ch++){System.out.print(ch);stack.push(ch);}System.out.println();//Now ,pop the characters off the stack util it is empty.System.out.println("Poping:");while (!stack.isEmpty()){ch = stack.pop();System.out.print(ch);}//-------------------------------------------------------------------System.out.println("\n\nNext,use 4-element stack to generate"+"some error.");//Generate some errors.SimpleStack smallStack = new SimpleStack(4);//Attempt to push 5 characters onto a 4-character stack.System.out.print("Pushing:");for (ch='1';ch<'6' ;ch++ ){System.out.print(ch);smallStack.push(ch);}//Attempt to pop 5 elements from a 4-character stack.System.out.print("Poping:");for (i=0;i<5 ;i++ ){ch = smallStack.pop();System.out.print(ch);}}}

原创粉丝点击