我負責在C中創建一個隊列數據結構作爲鏈表。我們的講師給了我們大量的代碼來實現一個堆棧,但我們必須調整它來創建一個隊列。我們的講師給我們的代碼最終不會像我爲隊列寫的代碼那樣完全編譯和分段。我對結構,malloc和C一般都很陌生,所以可能會有一些我忽略的東西顯而易見。使用結構和動態內存分配的隊列
這裏是我使用的代碼:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data; //contains the actual data
struct node *prev; //pointer to previous node (Closer to front)
struct node *next; //pointer to next node (Closer to back)
};
typedef struct node *Nodepointer;
struct queue{
Nodepointer front;
Nodepointer back;
};
typedef struct queue *Queuepointer;
main(){
Queuepointer myqueue; //create a queue called myqueue
init(myqueue); //initialise the queue
Nodepointer new = (Nodepointer)malloc(sizeof(struct node));
myqueue->front = new;
}
int init(Queuepointer q){
q = (Queuepointer)malloc(sizeof(struct queue));
q->front = NULL;
q->back = NULL;
}
的想法是,隊列結構「包含」在隊列中的第一和最後一個節點,並創建一個節點時,myQueue中被更新。但是,我甚至無法達到那個部分(流行和推動都是書面的,但爲了簡潔省略)。該代碼是在段錯誤行
myqueue->front = new;
用以下GDB輸出:
Program received signal SIGSEGV, Segmentation fault.
0x08048401 in main() at queue.c:27
27 myqueue->front = new;
任何想法,我做錯了嗎?
只是一個評論:避免使用關鍵字'新'。這是C++的一個保留字,如果稍後使用C++程序使用代碼,會遇到一些麻煩。啊,並且總是檢查malloc返回一個非NULL值(最佳做法)。 – Pierre 2010-03-21 20:19:26
關於術語的一個注意事項:這裏所說的更適當地稱爲*雙鏈表*,因爲每個節點都有向前和向後指針。在*單鏈接列表中,每個節點只有一個轉發指針。當一個人談到一個*鏈表時*有時是一個好主意,指定你在談論哪種。 – crazyscot 2010-03-21 20:30:44
皮埃爾,謝謝......我相信那是在講師的代碼中,但是我由於某種原因省略了它。 Crazyscot,你是對的,我的壞。今後會記住這一點,謝謝。 – 2010-03-21 20:32:57