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

简介: 【每日算法】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函数中为一个指针分配空间,之后将指针作为返回值返回(其实就是一个地址)

  1. 如果用字符数组承接输入的字符串,数组长度需要至少比字符串最大长度大1(字符串以'\0'结尾)
目录
相关文章
|
2天前
|
算法 C语言
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
|
2天前
|
算法 C语言
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
|
2天前
|
算法 Java
Java数据结构与算法:双向链表
Java数据结构与算法:双向链表
|
2天前
|
算法 Java
Java数据结构与算法:循环链表
Java数据结构与算法:循环链表
|
2天前
|
算法
【数据结构与算法 刷题系列】求带环链表的入环节点(图文详解)
【数据结构与算法 刷题系列】求带环链表的入环节点(图文详解)
|
2天前
|
算法
【数据结构与算法 刷题系列】判断链表是否有环(图文详解)
【数据结构与算法 刷题系列】判断链表是否有环(图文详解)
|
2天前
|
算法 程序员 数据处理
【数据结构与算法】使用单链表实现队列:原理、步骤与应用
【数据结构与算法】使用单链表实现队列:原理、步骤与应用
|
2天前
|
算法
【数据结构与算法 经典例题】随机链表的复制(图文详解)
【数据结构与算法 经典例题】随机链表的复制(图文详解)
|
2天前
|
算法 C语言
【数据结构与算法 经典例题】链表的回文结构(图文详解)
【数据结构与算法 经典例题】链表的回文结构(图文详解)
|
2天前
|
算法
【数据结构与算法 经典例题】反转链表(图文详解)
【数据结构与算法 经典例题】反转链表(图文详解)