Java implements a stack

Source: Internet
Author: User
Package zhangtingting; public class stacktest {private object [] stack; // number of elements; private int size; // The default length is 10; Public stacktest () {This (10 );} // You can also set the length, that is, capacity. Public stacktest (INT Len) {stack = new object [Len];} // returns the number of elements. Public int size () {return size;} // return the length of the array, that is, capacity. Public int capacity () {return stack. length ;}// implement a dynamic array; Public void ensurecapacity () {If (SIZE () = capacity () {object [] newstack = new object [size () * 3 /2 + 1]; system. arraycopy (stack, 0, newstack, 0, size (); stack = newstack ;}/// inbound stack; Public void push (Object O) {size ++; ensurecapacity (); stack [size-1] = O;} // empty; Public Boolean isempty () {return size = 0;} // out stack; public object POP () {// you must first specify NULL; If (isempty () {Throw new arrayindexoutofboundsexception ("cannot be blank ");} object o = stack [-- size]; stack [size] = NULL; return O;} public static void main (string [] ARGs) {stacktes T stack = new stacktest (3); string [] DATA = new string [] {"A", "B", "C"}; For (INT I = 0; I <data. length; I ++) {stack. push (data [I]); system. out. println (data [I] + "");} system. out. println ("************"); While (! Stack. isempty () {system. Out. println (stack. Pop () + "");}}}
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.