A circular link list is similar to singly link list. In Circular Link list the pointer of last node points to the first node. Circular Link List C Program

 

Let us see the below circular link list implementation in c

#include<stdio.h>
#include<stdlib.h>

typedef struct circularLink {
	int data;
	struct circularLink *next;
} cl;

void insertData(int data);
void PrintList();

cl *last = NULL;

int main() {
	// insert data
	insertData(4);
	insertData(3);
	insertData(5);
	insertData(6);
	insertData(8);

	// print circular list
	PrintList();
	printf("\n");
	return 0;
}

// insert at last
void insertData(int data) {
	// create new data
	cl *tmp = (cl *) malloc(sizeof(cl));
	tmp->data = data;

	// if the circular list is empty
	if (last == NULL) {
		last = tmp;
		// assign address of last node to first tmp node
		// to make circular list
		tmp->next = last;
	} else {
		tmp->next = last->next;
		last->next = tmp;
		last = tmp;
	}
}

void PrintList() {
	if (last == NULL) {
		printf("No items to print, list is empty\n");
	} else {
		cl *tmp;
		tmp = (cl *) malloc(sizeof(cl));
		tmp = last->next;
		do {
			printf("%d ", tmp->data);
			tmp = tmp->next;
		} while (tmp != last->next);
	}
}

 




Related Contents to follow