Java LinkedList-interview
Q1. What is a LinkedList in Java?
LinkedList is a doubly linked list implementation of the List and Deque interfaces in Java.
It allows dynamic memory allocation, supports insertion and deletion efficiently, and maintains insertion order.
Q2. What are the key features of LinkedList?
- Implements List, Deque, and Queue interfaces.
- Allows duplicate elements.
- Insertion and deletion are O(1) if reference is known.
- Provides methods like addFirst(), addLast(), removeFirst(), removeLast().
Q3. Write a simple program to demonstrate LinkedList usage.
OUTPUT
import java.util.*;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
list.addFirst("Mango");
list.addLast("Grapes");
System.out.println("First Element: " + list.getFirst());
System.out.println("All Elements: " + list);
}
}
OUTPUT
First Element: Mango
All Elements: [Mango, Apple, Banana, Grapes]
Q4. What are the disadvantages of LinkedList?
- Higher memory usage (stores extra pointers for each node).
- Slower random access (O(n) compared to ArrayList’s O(1)).
- Not cache-friendly, as elements are scattered in memory.
Q5. What is the time complexity of the following in LinkedList?
- Access by index → O(n)
- Insert at head/tail → O(1)
- Delete at head/tail → O(1)
Q6. In which scenarios is LinkedList preferred over ArrayList?
When there are frequent insertions/deletions at the beginning/middle of the list, and random access is not a priority.