gpt4 book ai didi

c - c中字符串的优先级队列

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:12 25 4
gpt4 key购买 nike

这个程序是优先级队列,我将字符串存储为数据,队列是使用链表创建的,具有最少编号的元素(作为优先级没有)具有更高的优先级,它将被插入到头节点等时间删除(弹出或出队)该元素将首先被删除。(例如,1 的优先级高于 2)

#include<stdio.h>
#include<stdlib.h>
struct node {
char *string;
int priority;
struct node* next;
};
struct node *head;
struct node* getnewnode(char *s,int p){
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->string=s;
newnode->priority=p;
newnode->next=NULL;

return newnode;
}
void push(char* str,int p){
struct node* node1=getnewnode(str,p);
if(head==NULL){ //if the element is inserted in empty list
head=node1;
}

if(head->priority > p )
{
node1->next=head;
head=node1;
}
else
{
struct node* temp=head;
while(temp->next!=NULL&&temp->priority <= p){
temp=temp->next;
}

while(temp->next!=NULL&&temp->priority <= p) is correct or not because if the pushed element priority is matching than this new element will be placed after the present one(having same priority)

      node1->next=temp->next;
temp->next=node1;

}

}
void pop(){
struct node* temp=head;
head=head->next;
free(temp);

}
char* peek(){
return head->string;
}
int main(){
head=NULL; //head is null initially
char a[10]="akash";
push(a,1);
char b[20]="rahul";
push(b,3);
printf("%s",peek());



}

它没有显示所需的输出,但它正在崩溃

int main(){
head=NULL;
char* a=(char *)malloc(sizeof(char)*10);
a="akash";
push(a,1);
char* b=(char *)malloc(sizeof(char)*10);
b="rahul";
push(b,3);
char* c=(char *)malloc(sizeof(char)*10);
c="neymar";
push(c,1);
printf("%s",peek());
pop();
printf("%s",peek());

}

我将 akash 的优先级设置为 1 rahul 为 2,将 neymar 再次设置为 1 它应该为最后两个 printf 语句打印 akash 和 neymar 但它正在打印 akash rahul @dbush

最佳答案

在您的push 函数中,如果head 为NULL,您将head 设置为新节点,然后稍后尝试再次将节点放入列表中。您最终会得到指向其自身的 next 字段,因此以后的插入将陷入无限循环。

插入空列表时,只需要将head设置为新节点即可,直接return就可以了。

if(head==NULL){        //if the element is inserted in empty list
head=node1;
return;
}

此外,您应该复制创建新节点时传入的字符串。否则,您最终可能会得到一个指向不再有效的内存的指针,或者指向同一个缓冲区的多个指针,只有最近的更新是可见的:

struct node* getnewnode(char *s,int p){
struct node* newnode = malloc(sizeof(struct node)); // don't cast return value of malloc
newnode->string = strdup(s); // create copy of given string
newnode->priority=p;
newnode->next=NULL;

return newnode;
}

关于c - c中字符串的优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52485725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com