Java LinkedList addFirst() Method Detailed Explanation
addFirst()YesLinkedListAn important method in the class, used to insert the specified element at the beginning of the linked list.
Method Syntax
public void addFirst(E e)
Parameter Description
E e: The element to be added at the beginning of the linked list
Return Value
This method has no return value (void).
How the addFirst() Method Works
addFirst()The working principle of the method can be briefly described as:
- Create a new node (Node) object
- Point the new node's
nextpointer to the current head node - Point the current head node's
prevpointer to the new node - Update the linked list's
headpointer to the new node - If the linked list was previously empty, also point the tail node to the new node
- Increase the linked list's size count (size++)
Time Complexity
The time complexity of the addFirst() method is O(1), because no matter how large the linked list is, it only needs to perform a fixed number of operations.
Usage Examples
Let's look at the specific usage of the method through a few examples.addFirst()Example 1: Basic Usage
Example 1: Basic Usage
Example
public class AddFirstExample {
public static void main(String[] args) {
// Add initial elements
LinkedList<String> fruits = new LinkedList<>();
"Original linked list: "
fruits.add("Banana");
fruits.add("Orange");
System.out.println(// Output: [Banana, Orange] + fruits); // Use addFirst() to add an element at the beginning
"Linked list after addition: "
fruits.addFirst("Apple");
System.out.println(// Output: [Apple, Banana, Orange] + fruits); Example 2: Consecutive Additions
}
}
Example 2: Consecutive Additions
Example
public class ContinuousAddFirst {
public static void main(String[] args) {
LinkedList<Integer> numbers = new LinkedList<>();
// Output: [1, 2, 3]
numbers.addFirst(3);
numbers.addFirst(2);
numbers.addFirst(1);
System.out.println(numbers); // Note the relationship between the order of addition and the final result
Example 3: Difference from the add() Method
}
}
Example 3: Difference from the add() Method
Example
public class AddVsAddFirst {
public static void main(String[] args) {
LinkedList<String> list1 = new LinkedList<>();
LinkedList<String> list2 = new LinkedList<>();
// Use the addFirst() method to add the same elements
list1.add("A");
list1.add("B");
list1.add("C");
"Using add(): "
list2.addFirst("C");
list2.addFirst("B");
list2.addFirst("A");
System.out.println(// Output: [A, B, C] + list1); "Using addFirst(): "
System.out.println(// Output: [A, B, C] + list2); // Although the final result is the same, the order of addition is reversed
Notes
}
}
Notes
1. Difference from the add() MethodaddFirst()The method adds elements to the end of the linked list by default
1. Difference from the add() Method
add()2. Difference from the offerFirst() MethodaddFirst()May throw an exception in a capacity-constrained queue
2. Difference from the offerFirst() Method
addFirst()instead of throwing an exceptionofferFirst()3. Null Value HandlingfalseAllows adding
3. Null Value Handling
LinkedListis legal.null4. Thread SafetyaddFirst(null)is not thread-safe; if used in a multi-threaded environment
4. Thread Safety
LinkedListPractical Application ScenariosaddFirst()The method is particularly useful in the following scenarios:
Practical Application Scenarios
addFirst()Since a stack is a "Last In, First Out" (LIFO) structure, addFirst() and removeFirst() can be used to simulate stack operations.
1. Implementing a Stack Structure
// Push to stack
Example
stack.addFirst("Task1"); // Pop from stack, returns "Task2"
stack.addFirst("Task2"); 2. Most Recently Used List
String top = stack.removeFirst(); When implementing a Most Recently Used (MRU) list, newly accessed items can be added to the beginning of the list.
2. Most Recently Used List
By adding elements one by one to a new list with addFirst(), list reversal can be achieved.
3. Reversal Operation
// Output: [3, 2, 1]
Example
LinkedList<Integer> reversed = new LinkedList<>();
for (Integer num : original) {
reversed.addFirst(num);
}
System.out.println(reversed); The method has very good performance in
Performance Considerations
addFirst()Creating a new nodeLinkedListAdjusting a few pointers
- No matter how large the linked list is, the time for these operations is constant (O(1) time complexity). This is in sharp contrast to the
- operation, which requires moving all existing elements (O(n) time complexity).
Therefore, if you need to frequently add elements at the beginning of a collection,ArrayListofadd(0, element)is a better choice than
.LinkedListFrequently Asked QuestionsArrayListQ1: Will addFirst() overwrite existing elements?
Frequently Asked Questions
Q1: Will addFirst() overwrite existing elements?
Q2: If the linked list is empty, will addFirst() still work?addFirst()Yes, if the linked list is empty,
Q2: If the linked list is empty, will addFirst() still work?
Q3: What is the difference between addFirst() and push()?addFirst()In
Q3: What is the difference between addFirst() and push()?
InLinkedListare exactly the same method.addFirst()andpush()is justpush()another name foraddFirst(), used to allowLinkedListto be used as a stack.
Q4: Why does my IDE prompt that addFirst() is a method of Deque?
BecauseLinkedListimplements theDequeinterface,addFirst()is actuallyDequea method defined in theLinkedListinterface, and
Summary
LinkedListofaddFirst()SummaryLinkedListThe method is an efficient operation that allows us to insert elements at the beginning of a linked list. Understanding this method is very important for effectively using
, especially in scenarios where elements need to be frequently inserted at the beginning of a collection.
addFirst()Key Points Review:- Inserts elements at the beginning of the linked list
- and
add()Time complexity is O(1) - Different insertion position from the add() method
- Commonly used to implement stack structures and most recently used lists
Requires additional synchronization in multi-threaded environmentsaddFirst()By using theLinkedListmethod reasonably, the performance advantages of
Java LinkedList