Untitled
unknown
plain_text
2 years ago
2.2 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *prev; struct node *next; } Node; Node *create_node(int data) { Node *new_node = (Node*)malloc(sizeof(Node)); new_node->data = data; new_node->prev = NULL; new_node->next = NULL; return new_node; } void insert_node(Node **head, int data) { Node *new_node = create_node(data); if (*head == NULL) { *head = new_node; return; } Node *current = *head; while (current->next != NULL) { current = current->next; } current->next = new_node; new_node->prev = current; } void delete_node(Node **head, int data) { if (*head == NULL) { printf("List is empty!\n"); return; } Node *current = *head; while (current != NULL) { if (current->data == data) { if (current->prev == NULL) { // delete head *head = current->next; if (*head != NULL) { (*head)->prev = NULL; } } else if (current->next == NULL) { // delete tail current->prev->next = NULL; } else { // delete middle node current->prev->next = current->next; current->next->prev = current->prev; } free(current); printf("Node with data %d has been deleted.\n", data); return; } current = current->next; } printf("Node with data %d not found.\n", data); } void display_list(Node *head) { if (head == NULL) { printf("List is empty!\n"); return; } printf("Doubly linked list:\n"); while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } int main() { Node *head = NULL; insert_node(&head, 5); insert_node(&head, 10); insert_node(&head, 15); insert_node(&head, 20); display_list(head); delete_node(&head, 10); display_list(head); delete_node(&head, 5); display_list(head); delete_node(&head, 20); display_list(head); delete_node(&head, 30); return 0; }
Editor is loading...