'Priority Queue using linked lists
I've been trying to implement a priority queue with the help of a linked list. However, I am unable to add data to the list when i use the add() function which i have used in my program below. Some help would be great!
The program requires me to sort various data into separate queues..with all elements in the same queue having the same priority.
i.e : Data: A, Priority : 1 Data: B, Priority : 2 Data: C, Priority : 1
then it should store the data as follows :
Q1 : A,C Q2 : B
My program is as follows. I think i am messing up the pointers that i send as parameters to the function add...
`#include<stdio.h>
#include<conio.h>
struct node{
char data[3];
struct node *next;
};
void del(struct node *);
void add(struct node *,struct node **);
void display(struct node *);
int main()
{
int i;
struct node *list[5];
struct node *q;
int pr,n;
for(i=0;i<5;i++)
list[i]=NULL;
printf("enter the no.of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
q=(struct node*)malloc(sizeof(struct node));
printf("Enter data");
scanf("%s",&(q->data));
printf("\npriority :");
scanf("%d",&pr);
pr--;
add(q,&list[pr]);
}
for(i=0;i<5;i++)
{
display(list[i]);
}
for(i=0;i<5;i++)
del(list[i]);
getch();
return 0;
}
void add(struct node *q,struct node **n)
{
if(*n==NULL)
{
*n=q;
return;
}
while((*n)->next!=NULL)
*n=(*n)->next;
(*n)->next=q;
q->next=NULL;
return;
}
void del(struct node *q)
{
if(q==NULL)
{
printf("Queue empty");
return;
}
while(q->next->next!=NULL)
q=q->next;
q->next=NULL;
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%s\t",q->data);
q=q->next;
}
printf("\n");
return;
}`
Thanks in advance! :)
Solution 1:[1]
What about the cycle in function "add"?
while((*n)->next!=NULL) *n=(*n)->next;
Didn't you mean this?
while((*n)->next!=NULL) n=&(*n)->next;
Solution 2:[2]
several problems I saw:
- in main, q->next should be set to null after "q=(struct node*)malloc(sizeof(struct node))", otherwise it could be anything;
- in del, you actually didn't delete anything (all resource allocated by "malloc" should be released by "free");
- also in del, "q->next" may be null, so "q->next->next" could crash the program
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alesak |
| Solution 2 | BenMorel |
