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); } }
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]
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!