数组实现栈

mac2024-04-18  27

题目:

数据结构——使用数组实现栈

自己实现一个栈,要求这个栈具有push()、pop()(返回栈顶元素并出栈)、peek() (返回栈顶元素不出栈)、isEmpty()、size()这些基本的方法。

import java.util.Arrays; /** * @Name: * @Description: 使用数组实现栈:自己实现一个栈,要求这个栈具有push()、pop()(返回栈顶元素并出栈)、peek() (返回栈顶元素不出栈)、isEmpty()、size()这些基本的方法。 * @Author:hutao2@myhexin.com * @Date:2019/10/31 13:49 */ public class Mystack { private int[] storage;//存放栈中元素的数组 private int capacity;//栈的容量 private int count;//栈中元素数量 private static final int GROW_FACTOR = 2; //不带初始容量的构造方法。默认容量为8 public Mystack(){ this.capacity = 8; this.storage = new int[8]; this.count = 0; } //带初始容量的构造方法 public Mystack(int initialCapacity){ if(initialCapacity < 1) throw new IllegalArgumentException("Capacity too small"); this.capacity = initialCapacity; this.storage = new int[initialCapacity]; this.count = 0; } //确保容量大小 private void ensureCapacity(){ int newCapacity = capacity * GROW_FACTOR; storage = Arrays.copyOf(storage,newCapacity); capacity = newCapacity; } //入栈 public void push(int value){ if(count == capacity){ ensureCapacity(); } storage[count++] = value; } //返回栈顶元素并出栈 private int pop(){ count--; if (count == -1) throw new IllegalArgumentException("Stack is empty"); return storage[count]; } //返回栈顶元素并出栈 private int peek(){ if(count == 0){ throw new IllegalArgumentException("Stack is empty"); }else{ return storage[count-1]; } } //判断是否为空 private boolean isEmpty(){ return count == 0; } //返回栈中元素的个数 private int size(){ return count; } public static void main(String[] args) { Mystack mystack = new Mystack(3); mystack.push(1); mystack.push(2); mystack.push(3); mystack.push(4); mystack.push(5); mystack.push(6); mystack.push(7); mystack.push(8); System.out.println(mystack.peek());//8 System.out.println(mystack.size());//8 for (int i = 0; i < 8; i++) { System.out.println(mystack.pop()); } System.out.println(mystack.isEmpty());//true mystack.pop();//报错:java.lang.IllegalArgumentException: Stack is empty. } }
最新回复(0)