链队的基本操作

/*************************************************************************
	> 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时不需要释放。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值