Posted on by Kalkicode
Code Circular Linked List

Delete all odd position nodes from circular linked list

In the problem of deleting all odd position nodes from a circular linked list, we are presented with a circular linked list data structure. The task is to remove nodes located at odd positions while maintaining the circular nature of the linked list.

Problem Statement

Given a circular linked list, we need to delete nodes located at odd positions (considering the first node as position 1). After the deletion, the circular structure of the linked list should still be preserved.

Example

Consider a circular linked list with the following elements: 12 -> 22 -> 32 -> 42 -> 52 -> 62 -> 72 -> 82. After deleting all odd position nodes, the list becomes: 12 -> 32 -> 52 -> 72.

Idea to Solve the Problem

Before Delete Odd position nodes After Delete Odd position nodes

To delete nodes at odd positions from a circular linked list, we need to traverse the list and remove nodes based on their positions. Since the list is circular, we'll need to update pointers to maintain the circular structure.

Pseudocode

Here's the pseudocode to delete all odd position nodes from a circular linked list:

function deleteOddPositionNodes(circularLinkedList):
    if circularLinkedList.head is NULL:
        return
    temp = circularLinkedList.head.next
    back = circularLinkedList.head
    
    while temp is not NULL and temp is not circularLinkedList.head:
        back.next = temp.next
        temp = back.next
        if temp is circularLinkedList.head:
            return
        back = temp.next
        temp = back.next

Algorithm Explanation

  1. Check if the linked list is empty. If it is, return.
  2. Initialize temp and back pointers for traversal.
  3. Traverse the list using the temp pointer. If the current node's position is odd, perform the deletion by updating the back.next pointer and moving the temp pointer.
  4. Move to the next node (back = temp.next).
  5. Move the temp pointer to the node following the next node (temp = back.next).
  6. If the traversal reaches the end of the list, update the temp pointer to NULL to stop further traversal.

Program List

Time Complexity

The time complexity of deleting all odd position nodes from a circular linked list is O(n), where n is the number of nodes in the circular linked list. Since we need to traverse the entire list to identify and remove odd position nodes, the time complexity is linear. The space complexity is O(1) as we are using only a constant amount of extra space for pointers.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment