Program to Create and Traverse Circular Linked List

Circular linked list Program to Create and Traverse nodes in C

#include<stdio.h> 
#include<conio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
    };
struct node *head=NULL;
struct node* createNode(){
    struct node *newNode = (struct node *)malloc(sizeof(struct node));
     
return (newNode);
    }
 
void insertNode(){
	struct node *temp,*ptr;
	temp=createNode();
	printf("enter the data you want to insert:");
	scanf("%d",&temp->data);
	temp->next=NULL;
	if(head==NULL){
		head=temp;
		head->next=head;
	}
	else{
		ptr=head;
		while(ptr->next!=head){
			ptr=ptr->next;
		}
	       ptr->next=temp;
	       temp->next=head;
	     }
    }
void viewList(){
    struct node* temp=head;
	if(temp==NULL){
		printf("list is empty");
	}
	else{
	    printf("Values of Cicular list \n");
		while(temp->next!=head)
		{
			printf("%d\t",temp->data);
			temp=temp->next;
		}
		printf("%d \t",temp->data);
	}
}
 
int menu(){
    int choice;
    printf("\n 1.Add value to the list");
    printf("\n 2.Travesre/View List");
    printf("\n 3.Exit");
    printf("\n Please enter your choice: \t");
    scanf("%d",&choice);
    return(choice);
}
void main(){
    printf("Program to Create and Traverse nodes in Circular linked list");
    while(1){
        switch(menu()){
            case 1:
                insertNode();
                break;
            case 2:
                viewList();
                break;
            case 3:
                exit(0);
            default:
                printf("invalid choice");
        }
    }
        getch();
    }

Output

Program to Create and Traverse nodes in Circular linked list
 1.Add value to the list
 2.Travesre/View List
 3.Exit
 Please enter your choice:      1
enter the data you want to insert:4

 1.Add value to the list
 2.Travesre/View List
 3.Exit
 Please enter your choice:      1
enter the data you want to insert:2

 1.Add value to the list
 2.Travesre/View List
 3.Exit
 Please enter your choice:      1
enter the data you want to insert:7

 1.Add value to the list
 2.Travesre/View List
 3.Exit
 Please enter your choice:      1
enter the data you want to insert:9

 1.Add value to the list
 2.Travesre/View List
 3.Exit
 Please enter your choice:      2
Values of Cicular list 
4       2       7       9 
 1.Add value to the list
 2.Travesre/View List
 3.Exit
 Please enter your choice:      3
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now