我想在C中编写一个单向链表。到目前为止,我只是得到分段错误。 我可能设置指针错了,但我只是不知道如何正确地做到这一点。C中的单个链接列表
该列表应该用于从最高优先级(在列表的开始处)到最低优先级(在列表的末尾)排序的“处理器”。头应该指向第一个元素,但不知何故我做错了。
的一切都在这里首先是代码:
struct process {
int id;
int priority;
struct process *next;
}
struct process *head = NULL;
void insert(int id, int priority) {
struct process * element = (struct process *) malloc(sizeof(struct process));
element->id = id;
element->priority = priority;
while(head->next->priority >= priority)
head = head->next;
element->next = head->next;
head->next = element;
// I put here a printf to result, which leads to segmenatition fault
// printf("%d %d\n", element->id, element->priority);
}
/* This function should return and remove element with the highest priority */
int pop() {
struct process * element = head->next;
if(element == NULL)
return -1;
head->next = element->next;
free(element);
return element->id;
}
/* This function should remove a element with a given id */
void popId(int id) {
struct process *ptr = head;
struct process *tmp = NULL;
while(prt != NULL) {
if(ptr->id == id) {
ptr->next = ptr->next->next;
tmp = ptr->next;
} else {
prt = ptr->next;
}
}
free(tmp);
}
不幸的是,我不能尝试pop()
和popId()
由于分段错误。
有人可以告诉我我做错了什么?
编辑:现在,我编辑了插入功能。它看起来像这样:
void insert(int id, int priority) {
struct process * element = (struct process *) malloc(sizeof(struct process));
struct process * temp = head;
element->id = id;
element->priority = priority;
if(head == NULL) {
head = element; // edited due to Dukeling
element->next = NULL;
} else {
while(temp->next != NULL && temp->next->priority >= priority)
temp = temp->next;
element->next = head->next;
head->next = element;
}
// I put here a printf to result, which leads to segmenatition fault
// printf("%d %d\n", element->id, element->priority);
}
但我仍然得到分段故障为pop()和popId()。我在这里错过了什么?
在存储器访问冲突期间经常出现分段错误。这将建议您检查处理指针的代码部分。 –
当你有0个元素时,考虑'while(head-> next-> priority ...)'。 '头部'的价值是什么? (如果你尝试弹出一个空栈,你会在'pop'中出现类似的问题。) –
你没有调试你的代码。 –