#include<stdio.h>
#include<malloc.h>
#define QElemtype int
#define status int
typedef struct QNode {
QElemtype data;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
status InitQueue(LinkQueue* Q) {
Q->front = Q->rear = (QNode*)malloc(sizeof(QNode));
Q->front->next = NULL;
return 1;
}
status EnQueue(LinkQueue* Q, int e) {
QNode* p = (QNode*)malloc(sizeof(QNode));
p->next = NULL;
p->data = e;
Q->rear->next = p;
}
status InQueue(LinkQueue* Q, int* e) {
QNode* p = (QNode*)malloc(sizeof(QNode));
p = Q->front->next;
e = p->data;
Q->front->next = p->next;
free(p);
}
status ReadLinkQueue(LinkQueue* Q) {
return Q->front->data;
}
int main()
{
LinkQueue Q;
InitQueue(&Q);
EnQueue(&Q, 1);
printf("%d", ReadLinkQueue(&Q));
}
为什么输出值是随机值而不是我想要的数字1呢?
修改如下,见注释,供参考:
#include<stdio.h>
#include<malloc.h>
#define QElemtype int
#define status int
typedef struct QNode {
QElemtype data;
struct QNode* next;
}QNode, * QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
status InitQueue(LinkQueue* Q) {
//Q->front = Q->rear = (QNode*)malloc(sizeof(QNode));修改
Q->rear = Q->front = NULL; //修改
return 1;
}
status EnQueue(LinkQueue* Q, int e) {
QNode* p = (QNode*)malloc(sizeof(QNode));
p->next = NULL;
p->data = e;
if (Q->rear != NULL) //修改
Q->rear->next = p; //修改
else
Q->front = p; //修改 队头
Q->rear = p; //修改 队尾
return 1; //修改
}
status InQueue(LinkQueue* Q, int* e) {
//QNode* p = (QNode*)malloc(sizeof(QNode));修改
if (Q->front == NULL) { //修改
Q->rear = NULL; //修改
*e = -1; //修改
return 0; //修改
}
QNode* p = Q->front; //修改
Q->front = p->next; //修改
*e = p->data; //e = p->data; 修改
free(p);
return 1; //修改
}
status ReadLinkQueue(LinkQueue* Q) {
if (Q->front == NULL) return 0;
return Q->front->data;
}
int main()
{
int e;
LinkQueue Q;
InitQueue(&Q);//初始化队列
EnQueue(&Q, 1);//入队
EnQueue(&Q, 2);
EnQueue(&Q, 3);
EnQueue(&Q, 4);
printf("队头元素值:%d\n\n", ReadLinkQueue(&Q));
printf("出队:\n");
InQueue(&Q, &e);//出队
printf("%d\n", e);
InQueue(&Q, &e);
printf("%d\n", e);
InQueue(&Q, &e);
printf("%d\n", e);
InQueue(&Q, &e);
printf("%d\n", e);
InQueue(&Q, &e);
printf("%d\n", e);
return 0;
}