微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java手写实现栈【数据结构与算法】

package algorithm;

import java.util.Arrays;
import java.util.Iterator;

/**

  • @author Administrator

  • @date 2022-09-12 16:38

  • 数组栈
    */
    public class MyArrayStack implements Iterable {
    // 定义一个数组
    private Object[] elementData;
    // 顶部的索引
    private int topIndex;
    // 构造方法确定栈的长度
    public MyArrayStack(int size) {
    this.elementData = new Object[size];
    }

    /**

    • 定义迭代器
    • @return
      */
      @Override
      public Iterator iterator() {
      return new MyArrayStackIter();
      }
      class MyArrayStackIter implements Iterator{
      @Override
      public boolean hasNext() {
      return topIndex != elementData.length;
      }
      @Override
      public E next() {
      return pop();
      }
      @Override
      public void remove() {
      pop();
      }
      }
      public boolean push(E element){
      // 判断扩容两倍
      if(topIndex >= elementData.length){
      elementData = Arrays.copyOf(elementData,elementData.length << 1);
      }
      elementData[topIndex++] = element;
      return true;
      }
      // 删除并出栈 是否删除就看topIndex本身的大小是否改变
      public E pop(){
      if(topIndex <= 0){
      throw new RuntimeException("栈为空");
      }
      return (E) elementData[--topIndex];
      }
      // 不删除出栈 栈顶元素
      public E peek(){
      if(topIndex <= 0){
      throw new RuntimeException("栈为空");
      }
      return (E) elementData[topIndex - 1];
      }
      public static void main(String[] args) {
      MyArrayStack myArrayStack = new MyArrayStack(5);
      myArrayStack.push("11");
      myArrayStack.push("22");
      myArrayStack.push("33");
      System.out.println("-----------");
      System.out.println(myArrayStack.pop());
      System.out.println(myArrayStack.pop());
      System.out.println(myArrayStack.pop());
      System.out.println(myArrayStack.pop());
      // Iterator iterator = myArrayStack.iterator();
      // while (iterator.hasNext()){
      // System.out.println(iterator.next());
      // }
      }
      }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐