lista de colas
Publicado por carlos (1 intervención) el 18/02/2003 22:52:00
alguien tiene un algoritmo en c de una lista de colas para implementar prioridad
Valora esta pregunta


0
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
int priority;
struct Node* next;
} Node;
Node* createNode(int data, int priority) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->priority = priority;
newNode->next = NULL;
return newNode;
}
void insert(Node** head, int data, int priority) {
Node* newNode = createNode(data, priority);
if (*head == NULL || (*head)->priority < priority) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL && current->next->priority >= priority) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
int removeHighestPriority(Node** head) {
if (*head ==NULL) {
printf("La lista está vacía.\n");
return -1; // Indica que la lista está vacía
}
Node* temp = *head;
int data = temp->data;
*head = (*head)->next;
free(temp);
return data;
}
void display(Node* head) {
while (head != NULL) {
printf("Dato: %d, Prioridad: %d\n", head->data, head->priority);
head = head->next;
}
}
int main() {
Node* head = NULL;
insert(&head, 10, 2);
insert(&head, 20, 1);
insert(&head, 30, 3);
printf("Lista de colas con prioridad:\n");
display(head);
printf("Elemento removido: %d\n", removeHighestPriority(&head));
printf("Lista después de remover el elemento de mayor prioridad:\n");
display(head);
return 0;
}