代码
#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;
}
问题
- 写init函数时,是将q作为变量传入函数,在函数里面分配内存,malloc会返回一个指向queue的指针(一个地址),此时相当于指针变量q是作为形参传入函数,所以对于在函数内的任何修改在主函数中不会体现;
正确的应该是在init函数中为一个指针分配空间,之后将指针作为返回值返回(其实就是一个地址)
- 如果用字符数组承接输入的字符串,数组长度需要至少比字符串最大长度大1(字符串以'\0'结尾)