21xrx.com
2024-09-19 10:10:38 Thursday
登录
文章检索 我的文章 写文章
使用Java如何实现数据结构中的栈
2023-06-13 01:26:45 深夜i     --     --
Java 数据结构

栈是一种常用的数据结构,在计算机科学中广泛应用。它是一种只允许在列表的一端进行插入和删除操作的线性数据结构。本文将介绍如何使用Java语言实现栈。

代码案例:


public class Stack {

  private int top; // 栈顶指针

  private int[] data; // 存放元素的数组

  private int capacity; // 栈容量

  // 构造器

  public Stack(int capacity) {

    this.capacity = capacity;

    this.data = new int[capacity];

    this.top = -1;

  }

  // 出栈

  public int pop() throws Exception {

    if (isEmpty()) {

      throw new Exception("Stack is empty.");

    }

    return data[top--];

  }

  // 入栈

  public void push(int val) throws Exception {

    if (isFull()) {

      throw new Exception("Stack is full.");

    }

    data[++top] = val;

  }

  // 查看栈顶元素

  public int peek() throws Exception {

    if (isEmpty()) {

      throw new Exception("Stack is empty.");

    }

    return data[top];

  }

  // 判断栈是否为空

  public boolean isEmpty() {

    return (top == -1);

  }

  // 判断栈是否已满

  public boolean isFull() {

    return (top == capacity - 1);

  }

}

在上述代码中,我们利用数组实现了一个栈,并提供了常见的操作方法。其中栈的容量是可控的,可以通过构造器进行设置。

本文介绍了如何用Java语言实现数据结构中的栈。栈是一种非常基础的数据结构,也是编程中经常用到的一种数据结构。通过学习本文中的内容,相信读者已经对栈有了更深入的了解。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复