Home > Java > javaTutorial > How to use LinkedList.addFirst() method to add elements to the head of a linked list in Java?

How to use LinkedList.addFirst() method to add elements to the head of a linked list in Java?

PHPz
Release: 2023-11-18 15:51:06
Original
1490 people have browsed it

How to use LinkedList.addFirst() method to add elements to the head of a linked list in Java?

The LinkedList class in Java provides the addFirst() method to add elements to the head of the linked list. The function of this method is to add an element to the beginning of the linked list and move other elements of the original linked list back.

The following is a sample code that uses the LinkedList.addFirst() method to add elements to the head of the linked list:

import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        // 创建一个空的LinkedList对象
        LinkedList<Integer> linkedList = new LinkedList<>();

        // 添加元素到链表的尾部
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.add(4);
        linkedList.add(5);

        System.out.println("添加元素前的链表:" + linkedList);

        // 使用addFirst()方法将元素添加到链表头部
        linkedList.addFirst(0);

        System.out.println("添加元素后的链表:" + linkedList);
    }
}
Copy after login

The above code creates an empty LinkedList object, and then uses the add() method respectively Add elements 1, 2, 3, 4, and 5 to the end of the linked list. Next, use the addFirst() method to add element 0 to the head of the linked list and print the contents of the linked list.

Run the above code, the output result is as follows:

添加元素前的链表:[1, 2, 3, 4, 5]
添加元素后的链表:[0, 1, 2, 3, 4, 5]
Copy after login

As you can see, the addFirst() method successfully added element 0 to the head of the linked list. In the output result, the contents of the linked list are [0, 1, 2, 3, 4, 5].

The above is the detailed content of How to use LinkedList.addFirst() method to add elements to the head of a linked list in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template