欢迎访问宙启技术站
智能推送

Java函数实现常用数据结构(如栈、队列等)的方法

发布时间:2023-07-06 10:42:08

在Java中,可以使用类和方法来实现常用的数据结构,如栈和队列。下面展示了如何实现这些数据结构的方法。

1. 栈(Stack):

栈是一种LIFO(Last In First Out)的数据结构,可以使用Java中的类ArrayList来实现。具体实现如下:

import java.util.ArrayList;

public class MyStack {
    private ArrayList<Integer> stack;

    public MyStack() {
        stack = new ArrayList<>();
    }

    public void push(int value) {
        stack.add(value);
    }

    public int pop() {
        if (stack.isEmpty()) {
            throw new EmptyStackException();
        }
        int index = stack.size() - 1;
        int value = stack.get(index);
        stack.remove(index);
        return value;
    }

    public int peek() {
        if (stack.isEmpty()) {
            throw new EmptyStackException();
        }
        return stack.get(stack.size() - 1);
    }

    public boolean isEmpty() {
        return stack.isEmpty();
    }
}

在上述代码中,使用ArrayList来实现栈的数据结构。push()方法将元素添加到栈的顶部,pop()方法将栈的顶部元素移除并返回它,peek()方法返回栈的顶部元素但不移除它,isEmpty()方法检查栈是否为空。

2. 队列(Queue):

队列是一种FIFO(First In First Out)的数据结构,可以使用Java中的类LinkedList来实现。具体实现如下:

import java.util.LinkedList;

public class MyQueue {
    private LinkedList<Integer> queue;

    public MyQueue() {
        queue = new LinkedList<>();
    }

    public void enqueue(int value) {
        queue.add(value);
    }

    public int dequeue() {
        if (queue.isEmpty()) {
            throw new EmptyQueueException();
        }
        return queue.removeFirst();
    }

    public int peek() {
        if (queue.isEmpty()) {
            throw new EmptyQueueException();
        }
        return queue.getFirst();
    }

    public boolean isEmpty() {
        return queue.isEmpty();
    }
}

在上述代码中,使用LinkedList来实现队列的数据结构。enqueue()方法将元素添加到队列的尾部,dequeue()方法将队列的头部元素移除并返回它,peek()方法返回队列的头部元素但不移除它,isEmpty()方法检查队列是否为空。

除了栈和队列,还有其他常用的数据结构,如链表、堆和树等,也可以使用类和方法进行实现。以上展示的实现仅为简单示例,实际应用中可能需要更复杂的逻辑和功能。