How to Implement Generic LinkedList in Java?
Last Updated :
14 Feb, 2023
Linked List is Linear Data Structures that store values in nodes. As we do know here each Node possesses two properties namely the value of the node and link to the next node if present so. Linked List can not only be of Integer data type but String, boolean, Float, Character, etc. We can implement such a “generic” Linked List Data Type that can store values of any data type.
There are 6 primary member functions of a linked list: E
- add (data): It adds an element at the end of the linked list
- add (position, data): It adds an element to any valid position in the linked list
- remove(key): It removes node that contains key from the linked list
- clear() : it clears the entire linked list
- empty(): It checks if the linked list is empty or not
- length(): It returns the length of the linked list
Note: Time complexity is of order N for adding and removing operations and of order 1 for other operations.
Illustration: An Integer Linked List {100,200,300,400} is represented looks like

Implementation:
Example
Java
// Java Program to Implement Generic Linked List
// Importing all input output classes
import java.io.*;
// Class 1
// Helper Class (Generic node class for LinkedList)
class node<T> {
// Data members
// 1. Storing value of node
T data;
// 2. Storing address of next node
node<T> next;
// Parameterized constructor to assign value
node(T data)
{
// This keyword refers to current object itself
this.data = data;
this.next = null;
}
}
// Class 2
// Helper class ( Generic LinkedList class)
class list<T> {
// Generic node instance
node<T> head;
// Data member to store length of list
private int length = 0;
// Default constructor
list() { this.head = null; }
// Method
// To add node at the end of List
void add(T data)
{
// Creating new node with given value
node<T> temp = new node<>(data);
// Checking if list is empty
// and assigning new value to head node
if (this.head == null) {
head = temp;
}
// If list already exists
else {
// Temporary node for traversal
node<T> X = head;
// Iterating till end of the List
while (X.next != null) {
X = X.next;
}
// Adding new valued node at the end of the list
X.next = temp;
}
// Increasing length after adding new node
length++;
}
// Method
// To add new node at any given position
void add(int position, T data)
{
// Checking if position is valid
if (position > length + 1) {
// Display message only
System.out.println(
"Position Unavailable in LinkedList");
return;
}
// If new position is head then replace head node
if (position == 1) {
// Temporary node that stores previous head
// value
node<T> temp = head;
// New valued node stored in head
head = new node<T>(data);
// New head node pointing to old head node
head.next = temp;
return;
}
// Temporary node for traversal
node<T> temp = head;
// Dummy node with null value that stores previous
// node
node<T> prev = new node<T>(null);
// iterating to the given position
while (position - 1 > 0) {
// assigning previous node
prev = temp;
// incrementing next node
temp = temp.next;
// decreasing position counter
position--;
}
// previous node now points to new value
prev.next = new node<T>(data);
// new value now points to former current node
prev.next.next = temp;
}
// Method
// To remove a node from list
void remove(T key)
{
// NOTE
// dummy node is used to represent the node before
// the current node Since in a Singly Linked-List we
// cannot go backwards from a node, we use a dummy
// node to represent the previous node. In case of
// head node, since there is no previous node, the
// previous node is assigned to null.
// Dummy node with null value
node<T> prev = new node<>(null);
// Dummy node pointing to head node
prev.next = head;
// Next node that points ahead of current node
node<T> next = head.next;
// Temporary node for traversal
node<T> temp = head;
// Boolean value that checks whether value to be
// deleted exists or not
boolean exists = false;
// If head node needs to be deleted
if (head.data == key) {
head = head.next;
// Node to be deleted exists
exists = true;
}
// Iterating over LinkedList
while (temp.next != null) {
// We convert value to be compared into Strings
// and then compare using
// String1.equals(String2) method
// Comparing value of key and current node
if (String.valueOf(temp.data).equals(
String.valueOf(key))) {
// If node to be deleted is found previous
// node now points to next node skipping the
// current node
prev.next = next;
// node to be deleted exists
exists = true;
// As soon as we find the node to be deleted
// we exit the loop
break;
}
// Previous node now points to current node
prev = temp;
// Current node now points to next node
temp = temp.next;
// Next node points the node ahead of current
// node
next = temp.next;
}
// Comparing the last node with the given key value
if (exists == false
&& String.valueOf(temp.data).equals(
String.valueOf(key))) {
// If found , last node is skipped over
prev.next = null;
// Node to be deleted exists
exists = true;
}
// If node to be deleted exists
if (exists) {
// Length of LinkedList reduced
length--;
}
// If node to be deleted does not exist
else {
// Print statement
System.out.println(
"Given Value is not present in linked list");
}
}
// Method
// To clear the entire LinkedList
void clear()
{
// Head now points to null
head = null;
// length is 0 again
length = 0;
}
// Method
// Returns whether List is empty or not
boolean empty()
{
// Checking if head node points to null
if (head == null) {
return true;
}
return false;
}
// Method
// Returning the length of LinkedList
int length() { return this.length; }
// Method
// To display the LinkedList
// @Override
public String toString()
{
String S = "{ ";
node<T> X = head;
if (X == null)
return S + " }";
while (X.next != null) {
S += String.valueOf(X.data) + " -> ";
X = X.next;
}
S += String.valueOf(X.data);
return S + " }";
}
}
// Class 3
// Main Class
public class GFG {
// main driver method
public static void main(String[] args)
{
// Integer List
// Creating new empty Integer linked list
list<Integer> list1 = new list<>();
System.out.println(
"Integer LinkedList created as list1 :");
// Adding elements to the above List object
// Element 1 - 100
list1.add(100);
// Element 2 - 200
list1.add(200);
// Element 3 - 300
list1.add(300);
// Display message only
System.out.println(
"list1 after adding 100,200 and 300 :");
// Print and display the above List elements
System.out.println(list1);
// Removing 200 from list1
list1.remove(200);
// Display message only
System.out.println("list1 after removing 200 :");
// Print and display again updated List elements
System.out.println(list1);
// String LinkedList
// Creating new empty String linked list
list<String> list2 = new list<>();
System.out.println(
"\nString LinkedList created as list2");
// Adding elements to the above List object
// Element 1 - hello
list2.add("hello");
// Element 2 - world
list2.add("world");
// Display message only
System.out.println(
"list2 after adding hello and world :");
// Print current elements only
System.out.println(list2);
// Now, adding element 3- "GFG" at position 2
list2.add(2, "GFG");
// Display message only
System.out.println(
"list2 after adding GFG at position 2 :");
// now print the updated List again
// after inserting element at second position
System.out.println(list2);
// Float LinkedList
// Creating new empty Float linked list
list<Float> list3 = new list<>();
// Display message only
System.out.println(
"\nFloat LinkedList created as list3");
// Adding elements to the above List
// Element 1 - 20.25
list3.add(20.25f);
// Element 2 - 50.42
list3.add(50.42f);
// Element 3 - 30.99
list3.add(30.99f);
// Display message only
System.out.println(
"list3 after adding 20.25, 50.42 and 30.99 :");
// Print and display List elements
System.out.println(list3);
// Display message only
System.out.println("Clearing list3 :");
// Now.clearing this list using clear() method
list3.clear();
// Now, print and display the above list again
System.out.println(list3);
}
}
Output :-
Integer LinkedList created as list1 :
list1 after adding 100,200 and 300 :
{ 100 -> 200 -> 300 }
list1 after removing 200 :
{ 100 -> 300 }
String LinkedList created as list2
list2 after adding hello and world :
{ hello -> world }
list2 after adding GFG at position 2 :
{ hello -> GFG -> world }
Float LinkedList created as list3
list3 after adding 20.25, 50.42 and 30.99 :
{ 20.25 -> 50.42 -> 30.99 }
Clearing list3 :
{ }
Time Complexity: O(n)
Auxiliary Space : O(n)
Similar Reads
How to Implement Stack in Java using LinkedList and Generics?
Prerequisites: Generics in JavaLinkedList in JavaWhat is Stack? Stack is a linear Data Structure that follows LIFO(Last In First Out) order while performing its operations. The main operations that are performed on the stack are mentioned below: push() : Â inserts an element at beginning of the stack
6 min read
Can We Implement Xor Linked List in Java?
As we all can depict from the below figure that doubly LinkedList requires two link fields in order to store the address of the next node and the address of the right node Right? So XOR Linked list Typically acts as Doubly LinkedList. Each node of XOR Linked List requires only a single pointer field
3 min read
Java Program to Implement LinkedList API
Linked List is a part of the Collection framework That is present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure in which the elements are not stored in contiguous locations and every element is a separate object with a data pa
10 min read
Convert HashMap to LinkedList in Java
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. LinkedList is a part of the Collection framework present in java.util package. This class is an implementa
2 min read
How to Implement Stack in Java Using Array and Generics?
Stack is a linear Data Structure that is based on the LIFO concept (last in first out). Instead of only an Integer Stack, Stack can be of String, Character, or even Float type. There are 4 primary operations in the stack as follows: push() Method adds element x to the stack.pop() Method removes the
5 min read
Implementing Generic Graph in Java
Prerequisite: Generic Class We can also use them to code for Graph in Java. The Graph class is implemented using HashMap in Java. As we know HashMap contains a key and a value, we represent nodes as keys and their adjacency list in values in the graph. Illustration: An undirected and unweighted gra
5 min read
Convert a HashSet to a LinkedList in Java
In Java, HashSet and LinkedList are linear data structures. These are majorly used in many cases. There may be some cases where we need to convert HashSet to LinkedList. So, in this article, we will see how to convert HashSet to LinkedList in Java. Java Program to Convert a HashSet to a LinkedList T
2 min read
How to Sort a LinkedList in Java?
A Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations.Sorting the nodes of a Singly Linked list in ascending order:Original ListSorted ListWe can sort the LinkedList by many sorting techniques:Selection SortInsertion sortQuick sortMerge sort Me
13 min read
Convert Array to LinkedList in Java
Array is contiguous memory allocation while LinkedList is a block of elements randomly placed in the memory which are linked together where a block is holding the address of another block in memory. Sometimes as per requirement or because of space issues in memory where there are bigger chunks of co
3 min read
How to Implement Queue in Java using Array and Generics?
The queue is a linear data structure that follows the FIFO rule (first in first out). We can implement Queue for not only Integers but also Strings, Float, or Characters. There are 5 primary operations in Queue: enqueue() adds element x to the front of the queuedequeue() removes the last element of
4 min read