Untitled
unknown
plain_text
2 months ago
3.2 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> struct node { int data1; struct node *next; struct node *prev; }; struct node *head = NULL; void createlist() { struct node *n1, *n2, *n3, *n4, *n5, *n6, *n7; n1 = (struct node *)malloc(sizeof(struct node)); n2 = (struct node *)malloc(sizeof(struct node)); n3 = (struct node *)malloc(sizeof(struct node)); n4 = (struct node *)malloc(sizeof(struct node)); n5 = (struct node *)malloc(sizeof(struct node)); n6 = (struct node *)malloc(sizeof(struct node)); n7 = (struct node *)malloc(sizeof(struct node)); n1->data1 = 10; n2->data1 = 20; n3->data1 = 30; n4->data1 = 40; n5->data1 = 50; n6->data1 = 60; n7->data1 = 70; n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n5; n5->next = n6; n6->next = n7; n7->next = n1; n1->prev = n7; n2->prev = n1; n3->prev = n2; n4->prev = n3; n5->prev = n4; n6->prev = n5; n7->prev = n6; head = n1; } void display() { if (head == NULL) { printf("List is empty.\n"); return; } struct node *temp = head; do { printf("%d ", temp->data1); temp = temp->next; } while (temp != head); printf("\n"); } void insert_at_head(int value) { struct node *newNode = (struct node *)malloc(sizeof(struct node)); newNode->data1 = value; if (head == NULL) { newNode->next = newNode; newNode->prev = newNode; head = newNode; return; } struct node *last = head->prev; newNode->next = head; newNode->prev = last; head->prev = newNode; last->next = newNode; head = newNode; } void insert_at_tail(int value) { struct node *newNode = (struct node *)malloc(sizeof(struct node)); newNode->data1 = value; if (head == NULL) { newNode->next = newNode; newNode->prev = newNode; head = newNode; return; } struct node *last = head->prev; newNode->next = head; newNode->prev = last; last->next = newNode; head->prev = newNode; } void insert_at_position(int value, int position) { struct node *newNode = (struct node *)malloc(sizeof(struct node)); newNode->data1 = value; if (position == 1) { insert_at_head(value); return; } struct node *temp = head; int count = 1; while (count < position - 1 && temp->next != head) { temp = temp->next; count++; } newNode->next = temp->next; newNode->prev = temp; temp->next->prev = newNode; temp->next = newNode; } int main() { createlist(); printf("Your Circular Doubly Linked List:\n"); display(); insert_at_head(5); printf("After inserting 5 at head:\n"); display(); insert_at_tail(100); printf("After inserting 100 at tail:\n"); display(); insert_at_position(25, 4); printf("After inserting 25 at position 4:\n"); display(); return 0; }
Editor is loading...
Leave a Comment