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

如何使用Java函数实现常见的数据结构,如栈和队列?

发布时间:2023-07-03 18:53:31

Java中可以使用类和接口来实现常见的数据结构,如栈和队列。下面将分别介绍如何使用Java函数实现栈和队列。

1. 栈的实现:

栈是一种后进先出(LIFO)的数据结构,可以使用数组或链表来实现。以下是使用链表实现栈的示例代码:

class Node {
    int data;
    Node next;
  
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
  
class Stack {
    private Node top;
  
    public Stack() {
        this.top = null;
    }
  
    public void push(int data) {
        Node newNode = new Node(data);
        if (this.top == null) {
            this.top = newNode;
        } else {
            newNode.next = this.top;
            this.top = newNode;
        }
        System.out.println(data + " pushed to stack");
    }
  
    public int pop() {
        if (this.top == null) {
            throw new EmptyStackException();
        }
        int data = this.top.data;
        this.top = this.top.next;
        return data;
    }
  
    public int peek() {
        if (top == null) {
            throw new EmptyStackException();
        }
        return this.top.data;
    }
  
    public boolean isEmpty() {
        return this.top == null;
    }
}

使用示例:

Stack stack = new Stack();

stack.push(1);
stack.push(2);
stack.push(3);

System.out.println(stack.pop()); // 输出3
System.out.println(stack.peek()); // 输出2
System.out.println(stack.isEmpty()); // 输出false

2. 队列的实现:

队列是一种先进先出(FIFO)的数据结构,可以使用数组或链表来实现。以下是使用数组实现队列的示例代码:

class Queue {
    private static final int MAX_SIZE = 1000;
    private int front, rear, size;
    private int[] array;
  
    public Queue() {
        this.front = 0;
        this.rear = -1;
        this.size = 0;
        this.array = new int[MAX_SIZE];
    }
  
    public void enqueue(int data) {
        if (isFull()) {
            throw new IllegalStateException("Queue is full");
        }
        this.rear = (this.rear + 1) % MAX_SIZE;
        this.array[this.rear] = data;
        this.size++;
        System.out.println(data + " enqueued to queue");
    }
  
    public int dequeue() {
        if (isEmpty()) {
            throw new NoSuchElementException("Queue is empty");
        }
        int data = this.array[this.front];
        this.front = (this.front + 1) % MAX_SIZE;
        this.size--;
        return data;
    }
  
    public int peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("Queue is empty");
        }
        return this.array[this.front];
    }
  
    public boolean isEmpty() {
        return this.size == 0;
    }
  
    public boolean isFull() {
        return this.size == MAX_SIZE;
    }
}

使用示例:

Queue queue = new Queue();

queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);

System.out.println(queue.dequeue()); // 输出1
System.out.println(queue.peek()); // 输出2
System.out.println(queue.isEmpty()); // 输出false

以上是使用Java函数实现栈和队列的示例。通过定义相应的类和接口以及实现对应的方法,就可以在Java中实现常见的数据结构。