Singly Linked List
A singly linked list is the simplest form, where each node points only to the next node. It is a one-way chain.
Basic Operations
public class SinglyLinkedList {
Node head;
// Insert at beginning
public void insertAtHead(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Insert at end
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
// Delete node with given value
public void delete(int key) {
if (head == null) return;
if (head.data == key) {
head = head.next;
return;
}
Node temp = head;
while (temp.next != null && temp.next.data != key) {
temp = temp.next;
}
if (temp.next != null) {
temp.next = temp.next.next;
}
}
// Traverse and print
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}
}
Two Minute Drill
- Singly linked list: each node points to next node only.
- Head reference holds the first node.
- Insert at head: O(1). Insert at end: O(n) without tail reference.
- Deletion requires finding previous node.
- Traversal: O(n) time.
Need more clarification?
Drop us an email at career@quipoinfotech.com
