Skip to content

Instantly share code, notes, and snippets.

@meldsza
Created October 3, 2018 12:48
Show Gist options
  • Save meldsza/d661ed95b65d822804b483a63e589539 to your computer and use it in GitHub Desktop.
Save meldsza/d661ed95b65d822804b483a63e589539 to your computer and use it in GitHub Desktop.
Circular Linked List using head in C lang
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *Node;
Node createNode(int info)
{
Node newNode = (Node)malloc(sizeof(struct node));
newNode->info = info;
newNode->next = newNode;
return newNode;
}
void deleteNode(Node x)
{
printf("Deleted data is %d\n", x->info);
free(x);
}
void insertRear(Node head, int info)
{
Node newNode = createNode(info);
Node last = head->next;
while (last->next != head)
last = last->next;
last->next = newNode;
newNode->next = head;
}
void deleteRear(Node head)
{
if (head->next == head)
{
puts("List is empty");
return;
}
Node slast = head->next;
while (slast->next->next != head)
slast = slast->next;
Node deleted = slast->next;
slast->next = head;
deleteNode(deleted);
}
void display(Node head)
{
if (head->next == head)
{
puts("List is empty");
return;
}
Node current = head->next;
puts("Contents of the Circular Linked list are");
while (current != head)
{
printf("%d ", current->info);
current = current->next;
}
puts("");
}
int main()
{
Node head = createNode(0);
int ex = 0, choice, item;
char name[50];
while (!ex)
{
puts("Enter your choice\n1 Insert rear\n2 Delete rear\n3 Display\n4 Exit");
scanf("%d", &choice);
switch (choice)
{
case 1:
puts("Enter the data");
scanf("%d", &item);
insertRear(head, item);
break;
case 2:
deleteRear(head);
break;
case 3:
display(head);
break;
default:
ex = 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment