Convert a Singly Linked List to Circular Linked List

Technology CommunityCategory: Linked ListsConvert a Singly Linked List to Circular Linked List
VietMX Staff asked 3 years ago

To convert a singly linked list to circular linked list, we will set next pointer of tail node to head pointer.

  • Create a copy of head pointer, let’s say temp.
  • Using a loop, traverse linked list till tail node (last node) using temp pointer.
  • Now set the next pointer of tail node to head node. temp\->next = head
Implementation
def convertTocircular(head):
    # declare a node variable
    # start and assign head
    # node into start node.
    start = head
    
    # check that
    while head.next
    # not equal to null then head
    # points to next node.
    while(head.next is not None):
      head = head.next
    
    #
    if head.next points to null
    # then start assign to the
    # head.next node.
    head.next = start
    return start