Singly Linked Lists
Singly Linked Lists
To create and manipulate singly linked lists in Java, including operations like insertion,
deletion, and searching.
// Create a node
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
if (head == null) {
head = new Node(new_data);
return;
}
new_node.next = null;
last.next = new_node;
return;
}
// Delete a node
void deleteNode(int position) {
if (head == null)
return;
if (position == 0) {
head = temp.next;
return;
}
// Find the key to be deleted
for (int i = 0; temp != null && i < position - 1; i++)
temp = temp.next;
temp.next = next;
}
// Search a node
boolean search(Node head, int key) {
Node current = head;
while (current != null) {
if (current.data == key)
return true;
current = current.next;
}
return false;
}
// Print the linked list
public void printList() {
Node tnode = head;
while (tnode != null) {
System.out.print(tnode.data + " ");
tnode = tnode.next;
}
llist.insertAtEnd(1);
llist.insertAtBeginning(2);
llist.insertAtBeginning(3);
llist.insertAtEnd(4);
llist.insertAfter(llist.head.next, 5);
System.out.println();
int item_to_find = 3;
if (llist.search(llist.head, item_to_find))
System.out.println(item_to_find + " is found");
else
System.out.println(item_to_find + " is not found");
}
}