Singly Linked List in Java
// Define a node class for singly linked list
class Node {
int data; // Holds the data
Node next; // Points to the next node
Node(int data) {
[Link] = data; // Set the data
[Link] = null; // Initially, next is null
// Singly linked list class
class SinglyLinkedList {
Node head; // Head points to the first node
// Add a node at the end
void append(int data) {
Node newNode = new Node(data); // Create a new node
if (head == null) {
head = newNode; // If list is empty, new node is head
return;
Node current = head; // Start from head
while ([Link] != null) {
current = [Link]; // Traverse to the last node
[Link] = newNode; // Link last node to new node
// Display the list
void display() {
Node current = head; // Start from head
while (current != null) {
[Link]([Link] + " -> "); // Print data
current = [Link]; // Move to next node
[Link]("null"); // End of list
}
Circular Linked List in Java
// Node class is reused here
class CircularLinkedList {
Node head = null; // Start of the list
Node tail = null; // End of the list
// Add a node to the circular list
void append(int data) {
Node newNode = new Node(data); // Create a new node
if (head == null) {
head = newNode; // First node becomes head
tail = newNode; // And also tail
[Link] = head; // Point to itself to make it circular
} else {
[Link] = newNode; // Link current tail to new node
tail = newNode; // Update tail
[Link] = head; // Make it circular again
// Display the circular list
void display() {
if (head == null) return; // Empty list check
Node current = head;
do {
[Link]([Link] + " -> "); // Print data
current = [Link]; // Move to next node
} while (current != head); // Stop when back at head
[Link]("(back to head)"); // Indicate circularity
Main
public class Main {
public static void main(String[] args) {
// Singly Linked List
SinglyLinkedList sList = new SinglyLinkedList();
[Link](10);
[Link](20);
[Link](30);
[Link](); // Output: 10 -> 20 -> 30 -> null
// Circular Linked List
CircularLinkedList cList = new CircularLinkedList();
[Link](1);
[Link](2);
[Link](3);
[Link](); // Output: 1 -> 2 -> 3 -> (back to head)