1. 程式人生 > >佇列的連結串列實現(C語言)

佇列的連結串列實現(C語言)

利用C語言實現一個簡單的有簡單功能的佇列(只有輸入輸出用的C++),其中對指標的除錯還是比較麻煩,這裡總結一些關於segmentation faults(段錯誤)的常見錯誤:
<1>定義了指標後記得初始化,在使用的時候記得判斷是否為NULL,向NULL指標寫入資料會引起段錯誤。
<2>在使用陣列的時候是否被初始化,陣列下標是否越界,陣列元素是否存在等,訪問了非法的記憶體。
<3>在變數處理的時候變數的格式控制是否合理等,int a; printf("%s",a ), 會訪問地址為a的記憶體空間,也會引發這種段錯誤。

下面附上程式碼

#include
<stdio.h> #include <iostream> #include <stdlib.h> using namespace std; #define FALSE 0 #define TRUE 1 typedef int elemtype; struct Node { elemtype data; Node *next; }; struct Queue { Node *front; Node *rear; }; void initQueue(Queue *q) { q->front = q->
rear = (Node *)malloc(sizeof(Node)); if (!q->front) { return; } q->front->next = NULL; } int isEmpty(Queue *q) { if (q->front == q->rear) { return TRUE; } else { return FALSE; } } void Enqueue(Queue *q, elemtype data) { Node *
repareInsert = (Node *)malloc(sizeof(Node)); if (repareInsert == NULL) { exit(0); } q->rear->data = data; q->rear->next = repareInsert; q->rear = repareInsert; } elemtype Dequeue(Queue *q) { if (isEmpty(q)) { exit(0); } Node *FrontTmp = q->front; elemtype data = q->front->data; q->front = q->front->next; free(FrontTmp); return data; } void MakeEmpty(Queue *q) { while (!isEmpty(q)) { Dequeue(q); } } void DisposeQueue(Queue *q) { Node *FrontTmp = q->front; while (FrontTmp != q->rear) { cout << FrontTmp->data << endl; FrontTmp = FrontTmp->next; } } int main() { Queue q; initQueue(&q); for (int i = 1; i <= 5; i++) { Enqueue(&q, i); } cout << "Dispose queue: " << endl; DisposeQueue(&q); cout << "dequeue: " << endl; while (!isEmpty(&q)) { cout << Dequeue(&q) << endl; } return 0; }