DEV Community

Deepikandas
Deepikandas

Posted on

#38 Known is a Drop! LinkedList implementing List interface

What is LinkedList in Java?
👉 LinkedList is a linear data structure implementation in Java that stores elements as nodes connected using pointers (links).

Instead of an array, it uses:
Node structure
Each node has:

  • data
  • reference to next node
  • reference to previous node  🔹 Key features ✔ 1. Dynamic size Grows and shrinks automatically No fixed capacity like arrays ✔ 2. Fast insert/delete No shifting required Just change links Example:

Insert B between A and C → just update pointers
✔ 3. Slow random access
list.get(5);

👉 Must traverse node-by-node → O(n) time
🔹 Constructors in LinkedList

✔ Default:

LinkedList<String> list = new LinkedList<>();
Enter fullscreen mode Exit fullscreen mode

✔ From collection:

LinkedList<String> list = new LinkedList<>(otherList);
Enter fullscreen mode Exit fullscreen mode

Important interfaces it implements

LinkedList implements:

List
Deque
Queue

So it can act like:

List
Stack
Queue


🔹 1. List methods (from List interface)

These work because LinkedList also behaves like a List:

add(E e)
add(int index, E e)
get(int index)
set(int index, E e)
remove(int index)
size()
contains(Object o)
indexOf(Object o)

package LinkedListPack;
import java.util.LinkedList;
import java.util.List;
public class TrainCoach {
    public void insertCoach(List list, String s) {
        System.out.println("Adding General coach after AC coaches");
        list.add(4, s);
        System.out.println(list);
    }

    public void removeCoach(List list, String s) {
        System.out.println("Removing S6 coach ");
        if (list.contains(s)) {
            list.remove(s);
            System.out.println("list" + list);
        } else {
            System.out.println("No such coach to remove from Train");
        }
    }

    public static void main(String[] args) {
        TrainCoach tc = new TrainCoach();
        List coaches = new LinkedList();
        coaches.add("Engine ");
        coaches.add("Ac Coach A1 ");
        coaches.add("AC Coach A2 ");
        coaches.add("AC coach A3 ");
        coaches.add("S1 ");
        coaches.add("S2 ");
        coaches.add("S3 ");
        coaches.add("S4 ");
        coaches.add("S5 ");
        coaches.add("S6 ");
        coaches.add("Caboose ");
        System.out.println("Coaches in train before change  " + coaches);
        tc.insertCoach(coaches, "General Coach");
        tc.removeCoach(coaches, "S6 ");
        System.out.println("Final Coaches in train   " + coaches);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)