Java簡單棧的實現

來源:互聯網
上載者:User
package com.handy.ds;public class SimpleStack {// 棧數組private int[] arrays;// 棧的容量private int capacity;// 棧元素個數private int size;    //自動成長大小private int autoSize=5;public SimpleStack(int capacity) {size = 0;this.capacity=capacity;arrays = new int[capacity];}/** * @return the arrays */public int[] getArrays() {return arrays;}/** * @param arrays *            the arrays to set */public void setArrays(int[] arrays) {this.arrays = arrays;}/** * @return the capacity */public int getCapacity() {return capacity;}/** * @param capacity *            the capacity to set */public void setCapacity(int capacity) {this.capacity = capacity;}/** * @return the size */public int getSize() {return size;}/** * @param size *            the size to set */public void setSize(int size) {this.size = size;}   //增長函數public void extend(int increment){int[] extendStack=new int[capacity+increment];capacity=capacity+increment;for(int i=0;i<size;i++)extendStack[i]=arrays[i];     arrays=extendStack;}// 出棧,返回棧頂元素,改變棧的狀態public int pop() {if (isEmpty() == true)return -1;elsereturn arrays[--size];}  // 進棧public void push(int number) {if (isFull() == true){System.out.println("棧已經滿啦!");//capacity=capacity+autoSize;//arrays=new int[capacity];extend( autoSize);System.out.println("自動成長!"+"大小:"+autoSize);arrays[size++] = number;}elsearrays[size++] = number;}// 判斷棧是否為空白public boolean isEmpty() {if (size == 0)return true;elsereturn false;}// 判斷棧是否滿public boolean isFull() {if (size == capacity)return true;elsereturn false;}// 取棧頂元素,但不改變棧的狀態public int stackTop() {if (isEmpty() == false)return arrays[size - 1];elsereturn -1;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.