Class LinkedList<T>
java.lang.Object
com.amritpandey23.dsalibrary.linkedlist.LinkedList<T>
- Type Parameters:
T- the type of elements stored in the linked list
A generic singly linked list implementation with common list operations.
-
Constructor Summary
ConstructorsConstructorDescriptionConstructs an empty linked list.LinkedList(T headVal) Constructs a linked list with an initial head node containing the specified value. -
Method Summary
Modifier and TypeMethodDescriptionvoidDeletes the first node in the linked list.voidDeletes the last node in the linked list.getFirst()Retrieves the first node in the linked list.getLast()Retrieves the last node in the linked list.getNodeAtPos(int position) Retrieves the node at a specified position in the linked list.voidinsertAtPos(T val, int position) Inserts a new node with the specified value at a specific position in the linked list.voidinsertFirst(T val) Inserts a new node with the specified value at the beginning of the linked list.voidinsertLast(T val) Inserts a new node with the specified value at the end of the linked list.voidprint()Prints the linked list in a readable format.
-
Constructor Details
-
LinkedList
public LinkedList()Constructs an empty linked list. -
LinkedList
Constructs a linked list with an initial head node containing the specified value.- Parameters:
headVal- the value of the initial head node
-
-
Method Details
-
getFirst
Retrieves the first node in the linked list.- Returns:
- the first node in the linked list
- Throws:
NoSuchElementException- if the list is empty
-
getLast
Retrieves the last node in the linked list.- Returns:
- the last node in the linked list
- Throws:
NoSuchElementException- if the list is empty
-
getNodeAtPos
Retrieves the node at a specified position in the linked list.- Parameters:
position- the position of the node to retrieve (0-based index)- Returns:
- the node at the specified position
- Throws:
NoSuchElementException- if the list is emptyIllegalArgumentException- if the position is out of bounds
-
print
public void print()Prints the linked list in a readable format. -
insertFirst
Inserts a new node with the specified value at the beginning of the linked list.- Parameters:
val- the value to insert
-
insertLast
Inserts a new node with the specified value at the end of the linked list.- Parameters:
val- the value to insert
-
insertAtPos
Inserts a new node with the specified value at a specific position in the linked list.- Parameters:
val- the value to insertposition- the position at which to insert the new node (0-based index)- Throws:
IllegalArgumentException- if the position is out of bounds
-
deleteFirst
public void deleteFirst()Deletes the first node in the linked list.- Throws:
NoSuchElementException- if the list is empty
-
deleteLast
public void deleteLast()Deletes the last node in the linked list.- Throws:
NoSuchElementException- if the list is empty
-