Implementing a circular linked list in Java involves creating a linked list where the last node's "next" pointer points back to the first node, forming a closed loop. Here's a step-by-step guide on how to implement a simple circular linked list in Java:
1. Define a Node class:
First, create a `Node` class to represent the elements in the circular linked list. Each node should contain a data element and a reference to the next node.
```java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
```
2. Create a CircularLinkedList class:
Next, create a `CircularLinkedList` class to manage the circular linked list. This class will include methods to insert, delete, traverse, and display elements in the list.
```java
public class CircularLinkedList {
private Node head;
private Node tail;
public CircularLinkedList() {
this.head = null;
this.tail = null;
}
// Method to insert a node at the end of the circular linked list
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
tail.next = head; // Connect the tail to the head to make it circular
}
// Method to delete a node by value
public void delete(int data) {
if (head == null) {
return; // List is empty
}
Node current = head;
Node previous = null;
while (current.data != data) {
if (current.next == head) {
return; // Data not found in the list
}
previous = current;
current = current.next;
}
if (current == head && current == tail) {
head = tail = null; // Only one node in the list
} else if (current == head) {
head = head.next;
tail.next = head;
} else if (current == tail) {
tail = previous;
tail.next = head;
} else {
previous.next = current.next;
}
}
// Method to traverse and display the circular linked list
public void display() {
if (head == null) {
return; // List is empty
}
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
3. Test the CircularLinkedList:
You can create an instance of the `CircularLinkedList` class and use it to insert, delete, and display elements in the circular linked list.
public class Main {
public static void main(String[] args) {
CircularLinkedList circularList = new CircularLinkedList();
circularList.insert(1);
circularList.insert(2);
circularList.insert(3);
circularList.insert(4);
System.out.print("Circular Linked List: ");
circularList.display(); // Output: 1 2 3 4
circularList.delete(3);
System.out.print("After deleting 3: ");
circularList.display(); // Output: 1 2 4
}
}
```
This example demonstrates the basic implementation of a circular linked list in Java, including insertion, deletion, and display operations. You can expand upon this foundation to add more functionality as needed for your specific use case.
0 Comments