我寫了一個程序,創建了12個具有隨機容量的表。我想通過插入來對這個雙向鏈表進行排序。雖然代碼編譯時沒有錯誤,但我得到了運行時錯誤。我不知道爲什麼。有沒有人可以幫助我?排序雙向鏈表時的運行時錯誤
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define MAX 12
struct Table {
int capacity;
struct Table *next;
struct Table *prev;
};
typedef void (*table_func_pnt) (struct Table *table);
struct Table *add_random_number(struct Table *head);
void insertion_sort(struct Table **head);
void list_tables(struct Table *head, table_func_pnt func);
void print_capacity(struct Table *table);
int main(int argc, char **argv)
{
srand(time(0));
struct Table *list = NULL;
for(int i = 0; i<MAX; ++i){
list = add_random_number(list);
}
list_tables(list,print_capacity);
printf("\n");
insertion_sort(&list);
list_tables(list,print_capacity);
return EXIT_SUCCESS;
}
struct Table *add_random_number(struct Table *head){
struct Table *table = malloc(sizeof(struct Table));
table->capacity = 2 + rand() % 10;
table->next = head;
return table;
}
void list_tables(struct Table *head, table_func_pnt func)
{
while(head){
func(head);
head = head->next;
}
}
void print_capacity(struct Table *table)
{
printf("%d ",table->capacity);
}
void insertion_sort(struct Table **head)
{
int n;
struct Table *curr;
curr = *head;
if(curr->next == NULL)
return;
struct Table *ptr;
struct Table *temp;
curr = curr->next;
while(curr != NULL){
n = 0;
ptr = curr;
temp = curr->prev;
curr = curr->next;
while(temp != NULL && temp->capacity > ptr->capacity){
n++ ;
temp = temp->prev;
}if(n){
ptr->prev->next = ptr->next;
if(ptr->next != NULL)
ptr->next->prev = ptr->prev;
if(temp == NULL){
temp = *head;
ptr->prev = NULL;
ptr->next = temp;
ptr->next->prev =ptr;
*head = ptr;
}else{
temp = temp->next;
temp->prev->next = ptr;
ptr->prev = temp->prev;
temp->prev = ptr;
ptr->next = temp;
}
}
}
}
嘗試在調試器中運行,找到發生崩潰的位置。 –
如果你想要一個雙向鏈表,你需要類似'if(head!= NULL){head-> prev = table;}'在函數add_random_number()中'' – francis
你是對的@francis – Rinzler