Java Linkedlist Addfirst
[ Java LinkedList](#)
* * *
`addFirst()` is an important method in the `LinkedList` class, used to insert a 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 to the beginning of the linked list
### Return Value
This method does not return any value (void).
* * *
## How the addFirst() Method Works
The working principle of the `addFirst()` method can be described as follows:
1. Create a new Node object
2. Point the new node's `next` pointer to the current head node
3. Point the current head node's `prev` pointer to the new node
4. Update the linked list's `head` pointer to the new node
5. If the linked list was previously empty, also point the tail node to the new node
6. Increment the linked list's size counter (size++)
### Time Complexity
The time complexity of the addFirst() method is O(1), because it only needs to perform a fixed number of operations regardless of how large the linked list is.
* * *
## Usage Examples
Let's look at the specific usage of the `addFirst()` method through several examples.
### Example 1: Basic Usage
## Instance
import java.util.LinkedList;
public class AddFirstExample {
public static void main(String[] args){
// Create a LinkedList
LinkedList fruits =new LinkedList();
// Add initial elements
fruits.add("Banana");
fruits.add("Orange");
System.out.println("Original linked list: "+ fruits);// Output: [Banana, Orange]
// Use addFirst() to add element at the beginning
fruits.addFirst("Apple");
System.out.println("Linked list after adding: "+ fruits);// Output: [Apple, Banana, Orange]
}
}
### Example 2: Continuous Addition
## Instance
import java.util.LinkedList;
public class ContinuousAddFirst {
public static void main(String[] args){
LinkedList numbers =new LinkedList();
// Continuously use addFirst() to add elements
numbers.addFirst(3);
numbers.addFirst(2);
numbers.addFirst(1);
System.out.println(numbers);// Output: [1, 2, 3]
// Note the relationship between addition order and final result order
}
}
### Example 3: Difference between add() and addFirst() Methods
## Instance
import java.util.LinkedList;
public class AddVsAddFirst {
public static void main(String[] args){
LinkedList list1 =new LinkedList();
LinkedList list2 =new LinkedList();
// Use add() method to add elements
list1.add("A");
list1.add("B");
list1.add("C");
// Use addFirst() method to add the same elements
list2.addFirst("C");
list2.addFirst("B");
list2.addFirst("A");
System.out.println("Using add(): "+ list1);// Output: [A, B, C]
System.out.println("Using addFirst(): "+ list2);// Output: [A, B, C]
// Although the final result is the same, the addition order is reversed
}
}
* * *
## Precautions
When using the `addFirst()` method, pay attention to the following points:
### 1. Difference from add() Method
* The `add()` method adds elements to the end of the linked list by default
* The `addFirst()` method adds elements to the beginning of the linked list
### 2. Difference from offerFirst() Method
* `addFirst()` may throw an exception in capacity-constrained queues
* `offerFirst()` returns `false` instead of throwing an exception in capacity-constrained queues
### 3. Null Value Handling
`LinkedList` allows adding `null` values, so `addFirst(null)` is legal.
### 4. Thread Safety
`LinkedList` is not thread-safe. If using `addFirst()` in a multi-threaded environment, external synchronization is required.
* * *
## Practical Application Scenarios
The `addFirst()` method is particularly useful in the following scenarios:
### 1. Implementing Stack Structure
Since a stack is a "Last In, First Out" (LIFO) structure, you can use addFirst() and removeFirst() to simulate stack operations.
## Instance
LinkedList stack =new LinkedList();
stack.addFirst("Task1");// Push
stack.addFirst("Task2");// Push
String top = stack.removeFirst();// Pop, returns "Task2"
### 2. Recently Used List
When implementing a Most Recently Used (MRU) list, newly accessed items can be added to the beginning of the list.
### 3. Reversal Operation
By adding elements one by one to a new list using addFirst(), list reversal can be achieved.
## Instance
LinkedList original =new LinkedList(Arrays.asList(1, 2, 3));
LinkedList reversed =new LinkedList();
for(Integer num : original){
reversed.addFirst(num);
}
System.out.println(reversed);// Output: [3, 2, 1]
* * *
## Performance Considerations
The `addFirst()` method performs very well in `LinkedList` because it only needs to:
1. Create a new node
2. Adjust a few pointers
Regardless of how large the linked list is, these operations take constant time (O(1) time complexity). This is in stark contrast to `ArrayList`'s `add(0, element)` operation, which needs to move all existing elements (O(n) time complexity).
Therefore, if you need to frequently add elements at the beginning of a collection, `LinkedList` is a better choice than `ArrayList`.
* * *
## Frequently Asked Questions
### Q1: Does addFirst() overwrite existing elements?
No, `addFirst()` only inserts a new element at the beginning of the linked list and does not overwrite any existing elements.
### Q2: Can addFirst() work if the linked list is empty?
Yes, if the linked list is empty, `addFirst()` will make the new element the first and only element of the linked list.
### Q3: What is the difference between addFirst() and push()?
In `LinkedList`, `addFirst()` and `push()` are exactly the same method. `push()` is just another name for `addFirst()`, used to make `LinkedList` usable as a stack.
### Q4: Why does my IDE suggest addFirst() is a method of Deque?
Because `LinkedList` implements the `Deque` interface, `addFirst()` is actually a method defined in the `Deque` interface, and `LinkedList` provides its implementation.
* * *
## Summary
The `addFirst()` method of `LinkedList` is an efficient operation that allows us to insert elements at the beginning of the linked list. Understanding this method is very important for effectively using `LinkedList`, especially in scenarios where frequent insertion at the beginning of a collection is required.
Key Points Review:
* `addFirst()` inserts elements at the beginning of the linked list
* Time complexity is O(1)
* Different insertion position compared to the `add()` method
* Commonly used to implement stack structures and recently used lists
* Requires additional synchronization in multi-threaded environments
By using the `addFirst()` method reasonably, you can fully leverage `LinkedList`'s performance advantages in specific scenarios.
[ Java LinkedList](#)
YouTip