Advertisement
STANAANDREY

sda priority q

Dec 3rd, 2023
921
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5.     int data;
  6.     struct Node* nxt;
  7. } Node;
  8.  
  9. Node* newNode(int data, 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->nxt = nxt;
  17.     return node;
  18. }
  19.  
  20. typedef struct {
  21.     Node* first;
  22.     Node* last;
  23. } PQueue;
  24.  
  25. int extract(PQueue pq) {
  26.     if (pq.last == NULL) {
  27.         perror("extract error");
  28.         exit(1);
  29.     }
  30.     return pq.last->data;
  31. }
  32.  
  33. void insert(PQueue *pq, int data) {
  34.     if (pq->first == NULL) {
  35.         pq->first = pq->last = newNode(data, NULL);
  36.         return;
  37.     }
  38.     if (pq->first->data > data) {
  39.         pq->first = newNode(data, pq->first);
  40.         return;
  41.     }
  42.     Node* aux = pq->first;
  43.     while (aux->nxt != NULL) {
  44.         if (aux->data < data && data < aux->nxt->data) {
  45.             aux->nxt = newNode(data, aux->nxt);
  46.             return;
  47.         }
  48.         aux = aux->nxt;
  49.     }
  50.     pq->last->nxt = newNode(data, NULL);
  51. }
  52.  
  53. void pop(PQueue *pq) {
  54.     Node* aux = pq->first;
  55.     while (aux->nxt != pq->last) {
  56.         aux = aux->nxt;
  57.     }
  58.     free(pq->last);
  59.     pq->last = aux;
  60.  
  61. }
  62.  
  63. void display(const PQueue *const pq) {
  64.     for (Node* node = pq->first; node != NULL; node = node->nxt) {
  65.         printf("%d ", node->data);
  66.     }
  67.     puts("");
  68. }
  69.  
  70. void initPq(PQueue* pq) {
  71.     pq->first = pq->last = NULL;
  72. }
  73.  
  74. void freePQ(PQueue* pq) {
  75.     Node* curr = pq->first;
  76.     Node* nxt = NULL;
  77.     while (curr) {
  78.         nxt = curr->nxt;
  79.         free(curr);
  80.         curr = nxt;
  81.     }
  82. }
  83.  
  84. int main(void) {
  85.     PQueue pq;
  86.     initPq(&pq);
  87.     insert(&pq, 12);
  88.     insert(&pq, 4);
  89.     insert(&pq, 1);
  90.     insert(&pq, 3);
  91.     insert(&pq, 5);
  92.     insert(&pq, 45);
  93.     insert(&pq, 40);
  94.     display(&pq);
  95.     freePQ(&pq);
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement