Advertisement
STANAANDREY

dll delete sda

Nov 11th, 2023
658
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5.     int data;
  6.     struct Node *prev, *nxt;
  7. } Node;
  8.  
  9. Node *newNode(int data, Node *prev, Node *nxt) {
  10.     Node* node = (Node*)malloc(sizeof(Node));
  11.     if (node == NULL) {
  12.         perror("");
  13.         exit(1);
  14.     }
  15.     node->data = data;
  16.     node->prev = prev;
  17.     node->nxt = nxt;
  18.     return node;
  19. }
  20.  
  21. void addToStart(Node **head, int data) {
  22.     Node* node = newNode(data, NULL, *head);
  23.     if ((*head) != NULL) {
  24.         (*head)->prev = node;
  25.     }
  26.     (*head) = node;
  27. }
  28.  
  29. void printList(const Node *const head) {
  30.     for (Node* tmp = head; tmp != NULL; tmp = tmp->nxt) {
  31.         printf("%d ", tmp->data);
  32.     }
  33.     putchar('\n');
  34. }
  35.  
  36. Node* searchNode(const Node *const head, int data) {
  37.     for (Node* tmp = head; tmp != NULL; tmp = tmp->nxt) {
  38.         if (tmp->data == data) {
  39.             return tmp;
  40.         }
  41.     }
  42.     return NULL;
  43. }
  44.  
  45. void deleteNode(Node **head, Node *target) {
  46.     if (target == *head) {
  47.         *head = target->nxt;
  48.         return;
  49.     }
  50.     target->prev->nxt = target->nxt;
  51.     if (target->nxt == NULL) {
  52.         return;
  53.     }
  54.     target->nxt->prev = target->prev;
  55. }
  56.  
  57. void deleteByValue(Node **head, int data) {
  58.     Node* target = searchNode(*head, data);
  59.     if (target != NULL) {
  60.         deleteNode(head, target);
  61.     }
  62. }
  63.  
  64. int main(void) {
  65.     Node* node = NULL;
  66.     addToStart(&node, 3);
  67.     addToStart(&node, 2);
  68.     addToStart(&node, 1);
  69.     deleteByValue(&node, 2);
  70.     addToStart(&node, 12);
  71.     printList(node);
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement