A simple example of a circular linked list of C language data structures

  • 2020-05-26 09:41:56
  • OfStack

A simple example of a cyclic linked list of C language data structures

Example code:


# include <stdio.h>
# include <stdlib.h>
typedef struct node // Defines the structure of nodes in a linked list 
{
 int code; 
 struct node *next;
}NODE,*LinkList; 

/* Error message output function */
void Error(char *message)
{
 fprintf(stderr,"Error:%s/n",message);
 exit(1);
}

// Create a circular linked list 
LinkList createList(int n)
{
 LinkList head; // The first node 
 LinkList p; // The currently created node 
 LinkList tail; // End node 
 int i;
 head=(NODE *)malloc(sizeof(NODE));// Create the header node of the circular list 
 if(!head)
 {
 Error("memory allocation error!/n");
 }
 head->code=1;
 head->next=head;
 tail=head;
 for(i=2;i<n;i++)
 {
 // Create the nodes of the circular list 
 p=(NODE *)malloc(sizeof(NODE));
 tail->next=p;
 p->code=i;
 p->next=head;
 tail=p;
 }
 return head;
}

Method 2:


// Create a circular linked list method 2( Software designer tutorial book method )
LinkList createList2(int n)
{
 LinkList head,p;
 int i;
 head=(NODE *)malloc(sizeof(NODE));
 if(!head)
 {
 printf("memory allocation error/n");
 exit(1);
 }
 head->code=1;
 head->next=head;
 for(i=n;i>1;--i)
 {
 p=(NODE *)malloc(sizeof(NODE));
 if(!p)
 {
  printf("memory allocation error!/n");
  exit(1);
 }
 p->code=i;
 p->next=head->next;
 head->next=p;
 }
 return head;
}



void output(LinkList head)
{
 LinkList p;
 p=head;
 do
 {
 printf("%4d",p->code);
 p=p->next;
 }
 while(p!=head);
 printf("/n");
}


void main(void)
{
 LinkList head;
 int n;
 printf("input a number:");
 scanf("%d",&n);
 head=createList(n);
 output(head);
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: