我想在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'中出現類似的問題。) –
你沒有調試你的代碼。 –