以下是桶排序程序的代碼。將鏈接列表作爲參數傳遞時出錯
typedef struct node_struct {
double d;
struct node_struct *next;
} node;
我使用插入排序,以
void insert(double value, int index, node *B[]) {
node *t;
if (B[index] == NULL) {
t = (node *)malloc(sizeof(node));
t->d = value;
t->next = NULL;
B[index] = t;
} else {
node *p0, *p1;
p0 = B[index];
p1 = p0 -> next;
while(p1 != NULL) {
if (p1 -> d > value) {
break;
}
p1 = p1->next;
p0 = p0->next;
}
t = (node *)malloc(sizeof(node));
t->d = value;
t->next = p1;
p0->next = t;
}
void Bucket_Sort(double A[], int n) {
int j, index;
double B[n];
node *B1;
B1 = (node *)malloc(sizeof(node));
for (int i = 0; i < n; i++) {
B[i] = 0;
}
B1->d = A[0];
B1->next = NULL;
for (int i = 1; i <= n; i++) {
index = (int) floor(n * A[i]);
insert(A[i], index, B1); // This part of the program is where I'm going wrong
}
for (int = 0; i < n; i++) {
printf("%f \n", B[i]);
}
}
當我嘗試調用插入功能,錯誤發生時說:「期待結構節點**值進行排序,但參數的類型結構節點*「
但是,如果我呼叫插入功能如下: insert(A [i],index,& B1); 然後在編譯時沒有給出錯誤,但是當我運行程序時會導致分段錯誤。有人可以幫我解決困惑嗎?
好吧,沒錯,'B1'是指向'node'的指針,而你的函數需要指向'node'的指針數組。 – mangusta
這個問題很混亂。所以,當你提到一個錯誤時,你怎麼稱呼這個函數呢? – mangusta
我用insert(A [i],index,&B1); – Raghuveer