【每日算法】AB7 用链表实现队列

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
    struct node* next;
    int data;
} node;

struct queue {
    int size;
    struct node* front;
    struct node* rear;
} queue;

struct queue* init() {
    struct queue* q;
    q = (struct queue*)malloc(sizeof(struct queue));
    q->front = NULL;
    q->rear = NULL;
    q->size = 0;
    return q;
}

void push(struct queue* q, int a) {
    struct node* n = (struct node*)malloc(sizeof(node));
    n->data = a;
    if (q->size == 0) {
        q->front = n;
        q->rear = n;
        n->next = NULL;
    } else {
        q->rear->next = n;
        n->next = NULL;
        q->rear = n;
    }
    q->size ++;
}

int pop(struct queue* q) {
    int res;
    if (q->size == 1) {
        res = q->front->data;
        struct node* tmp = q->front;
        free(tmp);
        q->front = NULL;
        q->rear = NULL;
    } else {
        res = q->front->data;
        struct node* tmp = q->front;
        q->front = tmp->next;
        free(tmp);
    }
    q->size --;
    return res;
}

int main() {
    int cnt;
    scanf("%d", &cnt);
    char mode[6];
    int data;
    struct queue* q = init();
    for (int i = 0; i < cnt; i ++) {
        scanf("%s", mode);
        if (strcmp(mode, "push") == 0) {
            scanf("%d", &data);
            push(q, data);
        } else if (strcmp(mode, "pop") == 0) {
            if (q->size == 0) {
                printf("error\n");
            } else {
                int res = pop(q);
                printf("%d\n", res);
            }
        } else if (strcmp(mode, "front") == 0) {
            if (q->size == 0) {
                printf("error\n");
            } else {
                printf("%d\n", q->front->data);
            }
        }
    }
    return 0;
}

问题

  1. 写init函数时,是将q作为变量传入函数,在函数里面分配内存,malloc会返回一个指向queue的指针(一个地址),此时相当于指针变量q是作为形参传入函数,所以对于在函数内的任何修改在主函数中不会体现;
    正确的应该是在init函数中为一个指针分配空间,之后将指针作为返回值返回(其实就是一个地址)
  2. 如果用字符数组承接输入的字符串,数组长度需要至少比字符串最大长度大1(字符串以’\0’结尾)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值