我的程序有以下結構:爲什麼要將節點放入該隊列中的頂層?
typedef struct Entry { // node
void *data; // whatever our data is, goes here
struct Entry *next; // next node
} Entry;
typedef struct {
int (*compare)(const void*a, const void *b); // compare func
Entry *top; // head
Entry *bottom; // tail
} *Queue;
,並用它們來創建一個隊列,這樣的:使用此
Queue create(int (*cmp)(const void*a, const void*b)) {
Queue Q = NULL;
Q = (Queue)malloc(sizeof(Queue));
Q->top = NULL;
Q->bottom = NULL;
Q->top = malloc(sizeof(Entry));
Q->bottom = malloc(sizeof(Entry));
Q->compare = cmp;
return Q;
}
插入:從給定主測試文件
void insert(Queue queue, void *data) {
// start at the top
Entry *slot = queue->top;
Entry *newNode = malloc(sizeof(Entry));
newNode->data = data;
newNode->next = NULL;
// is it an entirely empty queue?
if (que_empty(queue)) {
// put our data into the dummy slot
queue->top = newNode;
}
}
運行這是正確的,不能修改(要插入的數據在全局變量中):
int main(void) {
Queue up, down, fifo;
up = create(cmp_int64_ascend);
if(up == NULL) {
fputs("Cannot create ascending queue\n", stderr);
exit(EXIT_FAILURE);
}
down = create(cmp_int64_descend);
if(down == NULL) {
fputs("Cannot create descending queue\n", stderr);
exit(EXIT_FAILURE);
}
fifo = create(NULL);
if(fifo == NULL) {
fputs("Cannot create FIFO queue\n", stderr);
exit(EXIT_FAILURE);
}
puts("Testing the ascending queue");
process(up);
puts("\nTesting the descending queue");
process(down);
puts("\nTesting the FIFO queue");
process(fifo);
destroy(up);
destroy(down);
destroy(fifo);
return(0);
}
當我嘗試運行它時,它開始無休止地重複看起來像指針地址(例如,18087952)和崩潰。我奮鬥的那一行是queue-> top = newNode。
如何將newNode分配到隊列頂部?
您的代碼是不相符的。 'main'正在調用'que_create',但是你向我們展示了一個名爲'create'的函數。 – 2014-10-30 18:22:13
這是不正確的。 'Q =(隊列)malloc(sizeof(隊列));'。你沒有分配足夠的內存。你需要使用'Q =(隊列)malloc(sizeof(* Q));'。 – 2014-10-30 18:24:56