/*************************************************************************
> File Name: link_queue.c
> Author:zhangji
> Mail:mrzhangji@outlook.com
> Created Time: Wed 04 Oct 2023 05:20:51 PM CST
************************************************************************/
#include<stdio.h>
#include <stdlib.h>
typedef struct LinkNode{
int data;
struct LinkNode * next;
}Node;
typedef struct LinkQueue{
int count;
Node *front, *rear;
}LinkQueue;
int init(LinkQueue * q){
q->front = q->rear = NULL;
q->count = 0;
return 1;
}
void clear(LinkQueue* q){
while(q->front != NULL){
Node *p = q->front->next;
free(q->front);
q->front = p;
}
q->count = 0;
// free(q);
}
int push(LinkQueue* q, int x){
Node * node = (Node *)malloc(sizeof(Node));
node->data = x;
node->next = NULL;
if(q->rear != NULL){
q->rear->next = node;
q->rear = q->rear->next;
}else{
q->front = q->rear = node;
}
q->count ++;
return 1;
}
int isEmpty(LinkQueue * q){
return q->count > 0 ? 1 : 0;
}
int pop(LinkQueue *q, int * x){
if( isEmpty(q) ) return 0;
*x = q->front->data;
Node * p = q->front;
q->front = p->next;
free(p);
q->count --;
return 1;
}
void printQueue(LinkQueue * q){
Node * p = q->front;
while(p != NULL){
printf("%3d", p->data);
p = p->next;
}
}
void createQueueFromArray(LinkQueue * q, int arr[], int length){
for(int i = 0; i < length; i ++) push(q, arr[i]);
}
int main(){
LinkQueue q;
init(&q);
int arr[] = {1, 2, 3, 4, 5, 6};
createQueueFromArray(&q, arr, 6);
printQueue(&q);
clear(&q);
printQueue(&q);
return 0;
}
编码时出现的bug:push操作时,忘记更新q->rear。
q并不是动态分配内存,clear时不需要释放。