Javatpoint Logo
Javatpoint Logo

Q. Program to delete a new node from the end of the circular linked list.

Explanation

In this program, we will create a circular linked list and delete a node from the end of the list. If the list is empty, it will display the message "List is empty". If the list is not empty, we will loop through the list till second last node is reached. We will make second last node as the new tail, and this new tail will point to head and delete the previous tail.

Program to delete a new node from the end of the circular linked list

Circular linked list after deleting node from end

Program to delete a new node from the end of the circular linked list

Here, in the above list, D is the last node which needs to be deleted. We will iterate through the list till C. Make C as new tail and C will point back to head A.

Algorithm

  1. Define a Node class which represents a node in the list. It has two properties data and next which will point to the next node.
  2. Define another class for creating the circular linked list and it has two nodes: head and tail. It has two methods: deleteEnd() and display() .
  3. deleteEnd() will delete the node from the end of the list:
    1. It first checks whether the head is null (empty list) then, it will return from the function as there is no node present in the list.
    2. If the list is not empty, it will check whether list has only one node.
    3. If the list has only one node, it will set both head and tail to null.
    4. If the list has more than one node then, iterate through the loop till current.next!= tail.
    5. Now, current will point to the node previous to tail. Make current as new tail and tail will point to head thus, deletes the node from last.
  4. display() will show all the nodes present in the list.
    1. Define a new node 'current' that will point to the head.
    2. Print current.data till current will points to head again.
    3. Current will point to the next node in the list in each iteration.

Solution

Python

Output:

Original List: 
 1 2 3 4
Updated List: 
 1 2 3
Updated List: 
 1 2
Updated List: 
 1
Updated List: 
List is empty

C

Output:

Original List: 
 1 2 3 4
Updated List: 
 1 2 3
Updated List: 
 1 2
Updated List: 
 1
Updated List: 
List is empty

JAVA

Output:

Original List: 
 1 2 3 4
Updated List: 
 1 2 3
Updated List: 
 1 2
Updated List: 
 1
Updated List: 
List is empty

C#

Output:

Original List: 
 1 2 3 4
Updated List: 
 1 2 3
Updated List: 
 1 2
Updated List: 
 1
Updated List: 
List is empty

PHP

Output:

Original List: 
 1 2 3 4
Updated List: 
 1 2 3
Updated List: 
 1 2
Updated List: 
 1
Updated List: 
List is empty

Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA