Answer to Question #233303 in C for XYZ

Question #233303

Let a linked list consists of n number of nodes, where each node consists of a unique

number, a priority number (in between 1 to 5), and pointer to next node. Design the

algorithm/develop pseudocode to divide the nodes into different linked list where

each linked consists of nodes having same priority.



1
Expert's answer
2021-09-05T00:33:04-0400
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
   int dt;
   int prt;
   struct node* next;
} Node;
Node* newNode(int d, int p) {
   Node* tp = (Node*)malloc(sizeof(Node));
   tp->dt = d;
   tp->prt = p;
   tp->next = NULL;
   return tp;
}
int peek(Node** hd) {
   return (*hd)->dt;
}
void pop(Node** hd) {
   Node* tp = *hd;
   (*hd) = (*hd)->next;
   free(tp);
}
void push(Node** hd, int d, int p) {
   Node* start = (*hd);
   Node* tp = newNode(d, p);
   if ((*hd)->prt > p) {
      tp->next = *hd;
      (*hd) = tp;
   } else {
      while (start->next != NULL &&
      start->next->prt < p) {
         start = start->next;
      }
      tp->next = start->next;
      start->next = tp;
   }
}
int isEmpty(Node** hd) {
   return (*hd) == NULL;
}
int main() {
   Node* p = newNode(5, 1);
   push(&p, 1, 2);
   push(&p, 3, 4);
   push(&p, 5, 0);
   while (!isEmpty(&p)) {
      printf("%d ", peek(&p));
      pop(&p);
   }
   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS