Advertisement
Guest User

Untitled

a guest
Oct 30th, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. void que_insert(QueueADT queue, void *data) {
  2.     // create node w/ data
  3.     Node* n;
  4.     n = malloc(sizeof(n));
  5.     n->next = NULL;
  6.     n->previous = NULL;
  7.     n->data = data;
  8.  
  9.     // if compare function doesn't exist, place in front of queue
  10.     if(queue->cmp == NULL) {
  11.         n->next = queue->front;
  12.         queue->front->previous = n;
  13.         queue->front = n;
  14.         return;
  15.     }
  16.  
  17.     // if empty queue
  18.     if(queue->length == 0) {
  19.         // assign front and back to given node
  20.         printf(": first insert \n");
  21.         queue->front = n;
  22.         queue->back = n;
  23.     } else {
  24.         Node* curr = queue->front;
  25.         int first = 1;
  26.  
  27.         while(1) {
  28.             // if < first node in queue, reassign head
  29.             if(first && queue->cmp(data, curr->data) < 0) {
  30.                 printf(": first %ld %ld\n", (long int)data, (long int)curr->data);
  31.                 queue->front->previous = n;
  32.                 n->next = queue->front;
  33.                 queue->front = n;
  34.  
  35.                 printf("{\n  next: %ld,\n  prev: NULL\n}\n\n",
  36.                     (long int)n->next->data);
  37.                 break;
  38.             } else if(curr->next == NULL){
  39.                 // if > end reassign tail
  40.                 printf(": end\n");
  41.                 queue->back->next = n;
  42.                 n->previous = queue->back;
  43.                 queue->back = n;
  44.  
  45.                 printf("{\n  next: NULL,\n  prev: %ld\n}\n\n",
  46.                    (long int)n->previous->data);
  47.                 break;
  48.             } else if(queue->cmp(data, curr->next->data) < 0){
  49.                 // if middle check if next is less
  50.                 printf(": middle \n");
  51.                 n->next = curr;
  52.                 n->previous = curr->previous;
  53.                 curr->previous = n;
  54.  
  55.                 printf("{\n  next: %ld,\n  prev: %ld\n}\n\n",
  56.                     (long int)n->next->data, (long int)n->previous->data);
  57.                 break;
  58.             }
  59.  
  60.             first = 0;
  61.             curr = curr->next;
  62.         }
  63.         printf("insert success\n");
  64.     }
  65.     queue->length++;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement