Circular linked list

Circular linked list is one whose tail pointer again points to the head. When there is only one node i.e. the head, it points to itself. This list has an advantage of finding the head node in one shot. The operation is just tail pointer next. Find the visual representation of the circular linked list in the below figure.

Circular linked list - pictorial view

Circular Linked list

Circular linked list - Source Code

#include <stdio.h>
#include <conio.h>

typedef struct _clist_node
{
  int node_value;             /* To store value */
  struct _clist_node * next;  /* To pint next node */

}clist_node;

int main(int argc, char *argv[])
{
  int key, i;

  clist_node *head, *temp, *current;

  head = NULL;
  temp = NULL;
  current = NULL;
  printf ("Circular linked list demo application\n");
  do
  {
    printf ("Add a node [y/n] : ");
    key = getch();
    if(key == 'y')
    {
      temp = (clist_node *)malloc(sizeof(clist_node));
      if(temp != NULL)
      {
        printf ("Value of this node : ");
        scanf ("%d", &temp->node_value);
        
        if(head == NULL)
        {
          current = temp;
          head = temp;
          head->next = head;
        }
        else
        {
          current->next = temp;
          current = temp;
          temp->next = head;
        }
      }
      else
      {
        printf("Memory allocation error!");
        return -1;
      }

    }
    else
    {
      break;
    }

  } while (1);
  current = head;
  i = 0;
  printf ("List Contains:\n");
  while(current)
  {
    printf ("Node %d, Value: %d\n", i + 1, current->node_value);
    i++;
    current = current->next;
    if(current == head)
    {
      break;
    }
  }
  return 0;
}

Output

Circular linked list demo application
Add a node [y/n] : y
Value of this node : 1
Add a node [y/n] : y
Value of this node : 10
Add a node [y/n] : y
Value of this node : 100
Add a node [y/n] : n
List Contains:
Node 1, Value: 1
Node 2, Value: 10
Node 3, Value: 100

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#