Home Java javaTutorial Common linear data structures in Java and their implementation: Exploration from stack to queue

Common linear data structures in Java and their implementation: Exploration from stack to queue

Dec 26, 2023 pm 04:55 PM
stack queue linear data structure

Common linear data structures in Java and their implementation: Exploration from stack to queue

From stack to queue: Exploring common linear data structures in Java and how they are implemented

Introduction:
In computer science, data structures are the organization and implementation of A way to store data. One of them is linear data structure, which is characterized by a clear contextual relationship between data elements. In Java development, common linear data structures include stacks and queues, which are used very frequently. This article will explore in depth how stacks and queues are implemented in Java and provide specific code examples.

1. The concept and implementation of stack:
The stack is a Last In First Out (LIFO) data structure. Its characteristic is that insertion and deletion operations can only be performed on the top of the stack. In Java, there are two common implementations of stacks: array-based implementation and linked-list-based implementation.

  1. Array-based stack implementation:
    Array is a continuously stored data structure, which is very suitable for implementing stacks. The following is a sample code of an array-based stack class:
public class ArrayStack {
    private int[] stack;
    private int top;  // 栈顶指针

    public ArrayStack(int capacity) {
        stack = new int[capacity];
        top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == stack.length - 1;
    }

    public void push(int item) {
        if (isFull()) {
            throw new RuntimeException("Stack is full");
        }
        stack[++top] = item;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty");
        }
        return stack[top--];
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty");
        }
        return stack[top];
    }
}
Copy after login
  1. Linked list-based stack implementation:
    Linked list is a non-continuous storage data structure, which is also suitable for implementation stack. The following is a sample code of a stack class based on a linked list:
public class LinkedStack {
    private Node top;

    public LinkedStack() {
        top = null;
    }

    public boolean isEmpty() {
        return top == null;
    }

    public void push(int item) {
        Node newNode = new Node(item);
        newNode.next = top;
        top = newNode;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty");
        }
        int item = top.data;
        top = top.next;
        return item;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Stack is empty");
        }
        return top.data;
    }

    private class Node {
        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
}
Copy after login

2. The concept and implementation of queue:
The queue is a first in first out (FIFO) data structure. Its characteristic is that it can only insert elements at the end of the queue and delete elements at the head of the queue. In Java, there are two common implementations of queues: array-based implementation and linked-list-based implementation.

  1. Array-based queue implementation:
    Similar to the array-based stack implementation, the following is a sample code for an array-based queue class:
public class ArrayQueue {
    private int[] queue;
    private int front;  // 队头指针
    private int rear;  // 队尾指针

    public ArrayQueue(int capacity) {
        queue = new int[capacity + 1];  // 额外预留一个空位
        front = rear = 0;
    }

    public boolean isEmpty() {
        return front == rear;
    }

    public boolean isFull() {
        return (rear + 1) % queue.length == front;
    }

    public void enqueue(int item) {
        if (isFull()) {
            throw new RuntimeException("Queue is full");
        }
        queue[rear] = item;
        rear = (rear + 1) % queue.length;
    }

    public int dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty");
        }
        int item = queue[front];
        front = (front + 1) % queue.length;
        return item;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty");
        }
        return queue[front];
    }
}
Copy after login
  1. Queue implementation based on linked list:
    Similar to the stack implementation based on linked list, the following is a sample code of a queue class based on linked list:
public class LinkedQueue {
    private Node front;  // 队头指针
    private Node rear;  // 队尾指针

    public LinkedQueue() {
        front = null;
        rear = null;
    }

    public boolean isEmpty() {
        return front == null;
    }

    public void enqueue(int item) {
        Node newNode = new Node(item);
        if (isEmpty()) {
            front = newNode;
            rear = newNode;
        } else {
            rear.next = newNode;
            rear = newNode;
        }
    }

    public int dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty");
        }
        int item = front.data;
        front = front.next;
        if (front == null) {
            rear = null;
        }
        return item;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty");
        }
        return front.data;
    }

    private class Node {
        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
}
Copy after login

Conclusion:
Stack and queue are Java There are many ways to implement linear data structures commonly used in . This article introduces array-based and linked-list-based stack and queue implementations, and provides specific code examples. Developers can choose the appropriate implementation method according to actual needs to improve the efficiency and maintainability of the program.

The above is the detailed content of Common linear data structures in Java and their implementation: Exploration from stack to queue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between heap and stack The difference between heap and stack Jul 18, 2023 am 10:17 AM

The difference between heap and stack: 1. The memory allocation method is different. The heap is manually allocated and released by the programmer, while the stack is automatically allocated and released by the operating system. 2. The size is different. The size of the stack is fixed, while the stack is automatically allocated and released by the operating system. The size of is growing dynamically; 3. Data access methods are different. In the heap, data access is achieved through pointers, while in the stack, data access is achieved through variable names; 4. Data life cycle , In the heap, the life cycle of data can be very long, while in the stack, the life cycle of variables is determined by the scope in which they are located.

Analysis and optimization strategies for Java Queue queue performance Analysis and optimization strategies for Java Queue queue performance Jan 09, 2024 pm 05:02 PM

Performance Analysis and Optimization Strategy of JavaQueue Queue Summary: Queue (Queue) is one of the commonly used data structures in Java and is widely used in various scenarios. This article will discuss the performance issues of JavaQueue queues from two aspects: performance analysis and optimization strategies, and give specific code examples. Introduction Queue is a first-in-first-out (FIFO) data structure that can be used to implement producer-consumer mode, thread pool task queue and other scenarios. Java provides a variety of queue implementations, such as Arr

What are the differences between java heap and stack What are the differences between java heap and stack Dec 25, 2023 pm 05:29 PM

The difference between Java heap and stack: 1. Memory allocation and management; 2. Storage content; 3. Thread execution and life cycle; 4. Performance impact. Detailed introduction: 1. Memory allocation and management. The Java heap is a dynamically allocated memory area, mainly used to store object instances. In Java, objects are allocated through heap memory. When an object is created, the Java virtual machine Allocate corresponding memory space on the system, and automatically perform garbage collection and memory management. The size of the heap can be dynamically adjusted at runtime, configured through JVM parameters, etc.

Application of queue technology in message delay and message retry in PHP and MySQL Application of queue technology in message delay and message retry in PHP and MySQL Oct 15, 2023 pm 02:26 PM

Application summary of queue technology in message delay and message retry in PHP and MySQL: With the continuous development of web applications, the demand for high concurrency processing and system reliability is getting higher and higher. As a solution, queue technology is widely used in PHP and MySQL to implement message delay and message retry functions. This article will introduce the application of queue technology in PHP and MySQL, including the basic principles of queues, methods of using queues to implement message delay, and methods of using queues to implement message retries, and give

In Java, what is the difference between add() method and offer() method in queue? In Java, what is the difference between add() method and offer() method in queue? Aug 27, 2023 pm 02:25 PM

Queue in Java is a linear data structure with multiple functions. A queue has two endpoints and it follows the first-in-first-out (FIFO) principle for inserting and deleting its elements. In this tutorial, we will learn about two important functions of queues in Java, which are add() and Offer(). What is a queue? Queue in Java is an interface that extends the util and collection packages. Elements are inserted in the backend and removed from the frontend. Queues in Java can be implemented using classes such as linked lists, DeQueue, and priority queues. A priority queue is an extended form of a normal queue, where each element has a priority. The add() method of the queue is used to insert elements into the queue. It will define the element (as

Implementation plan of queue task monitoring and task scheduling in PHP and MySQL Implementation plan of queue task monitoring and task scheduling in PHP and MySQL Oct 15, 2023 am 09:15 AM

Implementation of queue task monitoring and task scheduling in PHP and MySQL Introduction In modern web application development, task queue is a very important technology. Through queues, we can queue some tasks that need to be executed in the background, and control the execution time and order of tasks through task scheduling. This article will introduce how to implement task monitoring and scheduling in PHP and MySQL, and provide specific code examples. 1. Working principle of queue Queue is a first-in-first-out (FIFO) data structure that can be used to

Queue and asynchronous processing optimization methods in PHP flash sale system Queue and asynchronous processing optimization methods in PHP flash sale system Sep 19, 2023 pm 01:45 PM

Queue and asynchronous processing optimization methods in the PHP flash sale system With the rapid development of the Internet, various preferential activities on e-commerce platforms, such as flash sales and rush sales, have also become the focus of users. However, this high concurrent user request is a huge challenge for traditional PHP applications. In order to improve the performance and stability of the system and solve the pressure caused by concurrent requests, developers need to optimize the flash sale system. This article will focus on the optimization methods achieved through queues and asynchronous processing in the PHP flash sale system, and give specific code examples.

How to implement queue message confirmation and consumption failure handling in PHP and MySQL How to implement queue message confirmation and consumption failure handling in PHP and MySQL Oct 15, 2023 pm 01:46 PM

Implementation methods of queue message confirmation and consumption failure handling in PHP and MySQL Queue is a common message passing mechanism, which can help solve high concurrency problems in the system and achieve asynchronous processing and decoupling. In the design of the queue, message confirmation and consumption failure handling are very important links. This article will explore how to use PHP and MySQL to implement queue message confirmation and consumption failure handling, and provide specific code examples. Message confirmation is in the queue. Message confirmation means that after the consumer successfully processes the message, it sends it to the queue.

See all articles