Java Program to Delete a Node From the Ending of the Circular Linked List
Last Updated :
21 Aug, 2022
In this article, we will learn about deleting a node from the ending of a circular linked list. Consider the linked list as shown below:
Example:
Input : 5->3->4->(head node)
Output: 5->3->(head node)
We will first initialize the list and add some data into it with the addNode() method and then proceed according to the below approaches:
Case 1: List is empty.
If the list is empty we will simply return.
Case 2: List is not empty
- delete():
- Return from the function if no node is present
- Sets both head and tail to null if only one node is there
- if it has more than one node then it removes the previous head node, the head will point to the next node in the list and tail will point to the new head.
- printNode() will print all the nodes present in the list as:
- Node current is defined which will point to the head
- Print current.val till it starts pointing to the head again
- In each iteration, it will point to the next node
Code:
Java
public class Main {
public class Node {
int val;
Node next;
public Node( int val) { this .val = val; }
}
public Node head = null ;
public Node tail = null ;
public void addNode( int val)
{
Node node = new Node(val);
if (head == null ) {
head = node;
tail = node;
node.next = head;
}
else {
tail.next = node;
tail = node;
tail.next = head;
}
}
public void delete()
{
if (head == null ) {
return ;
}
else {
if (head != tail) {
Node current = head;
while (current.next != tail) {
current = current.next;
}
tail = current;
tail.next = head;
}
else {
head = tail = null ;
}
}
}
public void printNode()
{
Node current = head;
if (head == null ) {
System.out.println( "List is empty" );
}
else {
do {
System.out.print( " " + current.val);
current = current.next;
} while (current != head);
System.out.println();
}
}
public static void main(String[] args)
{
Main list = new Main();
list.addNode( 5 );
list.addNode( 3 );
list.addNode( 4 );
System.out.println( "Original List: " );
list.printNode();
while (list.head != null ) {
list.delete();
System.out.println( "Updated List: " );
list.printNode();
}
}
}
|
Output
Original List:
5 3 4
Updated List:
5 3
Updated List:
5
Updated List:
List is empty
Time complexity: O(n) where n is no of nodes of circular linked list
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...