Use java's LinkedList.addFirst() function to add elements to the beginning of LinkedList
In Java programming, LinkedList is a commonly used data structure, which is very convenient when processing data. LinkedList is a doubly linked list which is very efficient for operating at the beginning and end.
In LinkedList, we can use the addFirst() function to add elements to the beginning of the linked list. This function can accept one parameter, which is the element to be added. Below is an example that shows how to use the addFirst() function to add elements to the beginning of a LinkedList.
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // 向链表的开头添加元素 linkedList.addFirst("Element 1"); linkedList.addFirst("Element 2"); linkedList.addFirst("Element 3"); // 打印链表中的元素 System.out.println("LinkedList: " + linkedList); } }
In the above code, we first create an empty LinkedList object. Then, use the addFirst() function three times to add three elements to the beginning of the linked list, namely "Element 1", "Element 2" and "Element 3". Finally, we print out the elements in the linked list.
Run this code, we will get the following output:
LinkedList: [Element 3, Element 2, Element 1]
As you can see, we successfully used the addFirst() function to add elements to the beginning of the LinkedList, and the newly added elements are The position in the linked list reflects the order in which they were added.
It should be noted that when using the addFirst() function to add elements to the beginning of LinkedList, since LinkedList is a two-way linked list, the time complexity of the adding operation is O(1), that is, it is not affected by the length of the linked list. Influence. This makes LinkedList ideal for frequent additions and deletions at the beginning and end.
To summarize, we can use the addFirst() function of LinkedList in Java to add elements to the beginning of the linked list. Through this function, we can easily realize the need to add elements at the beginning, and thanks to the characteristics of LinkedList, the adding operation is also very efficient. Whether in data processing or algorithm implementation, LinkedList's addFirst() function is a very useful tool.
The above is the detailed content of Add elements to the beginning of LinkedList using java's LinkedList.addFirst() function. For more information, please follow other related articles on the PHP Chinese website!