Algorithm (fourth edition) the Java implementation of the learning note can dynamically adjust the stack size of the array

Source: Internet
Author: User

Down (LIFO) stack: an implementation that dynamically adjusts the size of the array

Import Java.util.iterator;public class resizingarraystack<item> implements iterable<item>{private int N = 0 ;p rivate item[] A = (item[]) new Object[1];p ublic boolean isEmpty () {return N = = 0;} public int size () {return N;} public void resize (int max) {item[] temp = (item[]) new object[max];for (int i = 0; i < N; i++) {temp[i] = a[i];} A = temp;} Public Item Pop () {Item item = A[--n];a[n] = null;if (n > 0 && n = = a.length/4) {resize (A.LENGTH/2);} return item;} public void push (item item) {if (N = = a.length) {Resize (a.length * 2);} a[n++] = Item;} @Overridepublic iterator<item> Iterator () {//TODO auto-generated method Stubreturn new Reversearrayiterator ();} Private class Reversearrayiterator implements iterator<item>{private int i = N; @Overridepublic boolean hasnext () {/ /TODO auto-generated method Stubreturn i > 0;} @Overridepublic Item Next () {//TODO auto-generated method Stubreturn a[--i];} @Overridepublic void Remove () {//TODO auto-generated Method stub}}}

Advantages:
Almost (but not useless) achieves the best performance for the implementation of any collection class data type:
1. The time of each operation is independent of the collection size;
2. Space requirements always do not exceed the set size multiplied by a constant.

Disadvantages:
Some push () and pop () operations adjust the size of the array, which is proportional to the amount of time spent on the stack.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Algorithm (fourth edition) the Java implementation of the learning note can dynamically adjust the stack size of the array

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.