Java implementation sequence Stack

Source: Internet
Author: User

Code for the sequential stack class:

Package Sequencestack;public class Sequencestack {private int stack_init_size = 5;//Stack's original size private int INCREMENT =1;//stack increment Size private Object []stack = null;private int base;private int top;private int stacksize;/** * Initialization stack * */void Initstack () {Sta ck = new Object[stack_init_size];base=0;top=0;stacksize=0;} /** * into the stack * */void push (Object o) {if (top-base>=stack_init_size) {System.out.println ("expansion stack"); Stack_init_size=stack_init_size+increment;object []temp = new Object[stack_init_size];for (int i=0;i<stacksize;i+ +) {Temp[i]=stack[i];} Stack=null; Stack=temp;} Stack[stacksize] = o;stacksize++;top++;} /** * out of Stack * */object pop () {Object o = null;if (top==base) {System.out.println ("no elements in stack!") return null ");} else{o=stack[--top];stacksize--;} return o;} /** * Take the top element of the stack * */object GetTop () {Object o = null;if (top==base) {System.out.println ("There are no elements in the stack!") return null ");} ELSE{O=STACK[TOP-1];} return o;} /** * Print Stack * */void print () {System.out.print ("Print Stack:"), for (int i=0;i<stacksize;i++) {System.out.print (stack[i]+ "\ t");} System.out.println ();}}

Sequential stack test code:

Package Sequencestack;public class Sequencestackmain {public static void main (string[] args) {Sequencestack sstack = new S Equencestack (); Sstack.initstack (); Sstack.pop (); Sstack.push (1); Sstack.push (2); Sstack.push (3); Sstack.push (4); Sstack.push (5); Sstack.push (6); Sstack.push (3); Sstack.print (); Sstack.pop (); Sstack.pop (); Sstack.pop (); SStack.pop ( ); Sstack.print (); System.out.println ("Take the top element of the stack:" +sstack.gettop ()); Sstack.print ();}}

  

Java implementation sequence Stack

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.