1, using one-dimensional data to simulate the stack structure
Public classstack1{//One-dimensional data simulation stack structureobject[] elements; //The default stack has a capacity of 5 PublicStack1 () { This(5);//This is the reuse of code and can also be written as elements = new object[5]; } PublicStack1 (intmax) {Elements=NewObject[max]; } //Analog Stack pointers intindex; //pressure Stack Method Public voidPush (Object Element)throwsstack1operationexception{if(Index = =elements.length) { Throw NewStack1operationexception ("The STACK1 has been full"); } Elements[index++] =element; } //Stack Method PublicObject pop ()throwsstack1operationexception{if(Index = = 0){ Throw NewStack1operationexception ("The Stack1 has been empty!"); } returnelements[--index]; } }
2. Custom stack Exception class
Public class extends exception{ publicvoid stack1operationexception () { }; Public stack1operationexception (String msg) { super(msg); } }
3. Testing
Public classteststack1{ Public Static voidMain (string[] args) {Stack1 s=NewStack1 (); User U1=NewUser ("Jack", 23); User U2=NewUser ("Ford", 24); User U3=NewUser ("King", 25); User U4=NewUser ("Smith", 26); User U5=NewUser ("COOK", 27); User U6=NewUser ("Zhangsan", 28); Try{s.push (U1); S.push (U2); S.push (U3); S.push (U4); S.push (U5); S.push (U6); }Catch(stack1operationexception e) {e.printstacktrace (); } Try{System.out.println (S.pop ()); System.out.println (S.pop ()); System.out.println (S.pop ()); System.out.println (S.pop ()); System.out.println (S.pop ()); }Catch(stack1operationexception e) {e.printstacktrace (); } }}classuser{String name; intAge ; User (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString toString () {return"User[name=" +name+ ", age=" +age+ "]"; }}
One-dimensional array simulation data structure-------stack