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;
10 
11  int main(int argc, char *argv[])
12  {
13    int key, i;
14 
15    clist_node *head, *temp, *current;
16 
17    head = NULL;
18    temp = NULL;
19    current = NULL;
20    printf ("Circular linked list demo application\n");
21    do
22    {
23      printf ("Add a node [y/n] : ");
24      key = getch();
25      if(key == 'y')
26      {
27        temp = (clist_node *)malloc(sizeof(clist_node));
28        if(temp != NULL)
29        {
30          printf ("Value of this node : ");
31          scanf ("%d", &temp->node_value);
32          
33          if(head == NULL)
34          {
35            current = temp;
36            head = temp;
37            head->next = head;
38          }
39          else
40          {
41            current->next = temp;
42            current = temp;
43            temp->next = head;
44          }
45        }
46        else
47        {
48          printf("Memory allocation error!");
49          return -1;
50        }
51 
52      }
53      else
54      {
55        break;
56      }
57 
58    } while (1);
59    current = head;
60    i = 0;
61    printf ("List Contains:\n");
62    while(current)
63    {
64      printf ("Node %d, Value: %d\n", i + 1, current->node_value);
65      i++;
66      current = current->next;
67      if(current == head)
68      {
69        break;
70      }
71    }
72    return 0;
73  }

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

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

 Vote 0

Similar topics related to this section

Data Structures using array, Linked List, Single Linked list, Doubly Linked list, Circular Linked list, Doubly Circular Linked list, Queue, reverse single linked list, delete single linked list,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan