Java Basics - LinkedList Collection Implements Stacks and Queues

(1) Features of LinkedList:

  • The underlying data structure is a double-linked list, the query is slow, and the speed of the first and last operations is extremely fast, so there are many unique APIs for the first operation.

(2) Unique functions of the LinkedList collection:

method name illustrate
public void addFirst(E e) inserts the specified element at the beginning of this list
public void addLast(E e) Appends the specified element to the end of this list
public E getFirst() returns the first element in this list
public E getLast() returns the last element of this list
public E removeFirst() Removes and returns the first element in this list
public E removeLast() removes and returns the last element from this list

(3) LinkedList collection implements stack and queue code:

import java.util.LinkedList;

/**
 * LinkedList实现栈和队列结构(双链表)
 */
public class ListDemo01 {
    public static void main(String[] args) {
        //栈:先进后出
        LinkedList<String> stack = new LinkedList<>();
        //压栈,入栈    可用stack.push("第1个");或者以下格式
        stack.addFirst("第1个");
        stack.addFirst("第2个");
        stack.addFirst("第3个");
        stack.addFirst("第4个");
        System.out.println(stack);//[第4个, 第3个, 第2个, 第1个]
        //出栈 弹栈     可用stack.pop();或者以下格式
        System.out.println(stack.removeFirst());//第4个
        System.out.println(stack.removeFirst());//第3个
        System.out.println(stack.removeFirst());//第2个
        System.out.println(stack);//[第1个]

        //队列:先进先出
        LinkedList<String> queue = new LinkedList<>();
        //入队    可用queue.offerLast();或者以下格式
        queue.addLast("1号");
        queue.addLast("2号");
        queue.addLast("3号");
        queue.addLast("4号");
        System.out.println(queue);//[1号, 2号, 3号, 4号]
        //出队
        System.out.println(queue.removeFirst());//1号
        System.out.println(queue.removeFirst());//2号
        System.out.println(queue.removeFirst());//3号
        System.out.println(queue);//[4号]

    }
}

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/130025833