这是本人对队列链式结构综合运用写的一段代码,但是输出入队的data值是乱码,不是入队的值,请问为什么会这样的呢?
#include<stdio.h>
#include<stdlib.h>
typedef struct linknode
{
int data;
struct linknode *next;
}linknode;
typedef struct
{
linknode *front,rear;
}linkqueue;
void initqueue(linkqueue &L)
{
L.front=L.rear=(linknode)malloc(sizeof(linknode));
L.front->next=NULL;
}
void enqueue(linkqueue L,int x)
{
linknode p=(linknode)malloc(sizeof(linknode));
p->data=x;
p->next=NULL;
L.rear->next=p;
L.rear=p;
}
int dequeue(linkqueue L,int &x)
{
if(L.front==L.rear)
return -1;
linknode *p=L.front->next;
x=p->data;
L.front->next=p->next;
if(L.rear==p)
L.rear=L.front;
else
free(p);
return 1;
}
int isempty(linkqueue L)
{
if(L.front==L.rear)
return 1;
else
return -1;
}
int main()
{
int x;
linkqueue s;
initqueue(s);
enqueue(s,3);
printf("%d\n",s.rear->data);
if(dequeue(s,x))
printf("%d\n",dequeue(s,x));
if(isempty(s))
printf("%d\n",isempty(s));
}
这是本人对队列链式结构综合运用写的一段代码,但是输出入队的data值是乱码,不是入队的值,请问为什么会这样的呢?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- qzjhjxj 2022-08-01 21:09关注
修改处见注释,供参考:
#include <stdio.h> #include <stdlib.h> typedef struct linknode { int data; struct linknode *next; }linknode; typedef struct { linknode *front,*rear; }linkqueue; void initqueue(linkqueue &L) { L.front=L.rear=(linknode*)malloc(sizeof(linknode)); L.front->next=NULL; } void enqueue(linkqueue &L,int x) //修改 { linknode* p=(linknode*)malloc(sizeof(linknode)); p->data = x; p->next = NULL; if (L.front->next == NULL) //修改 L.front->next = p; //修改 L.rear->next = p; L.rear = p; } int dequeue(linkqueue &L,int &x) //修改 { if(L.front == L.rear) return -1; linknode *p = L.front->next; x = p->data; L.front->next = p->next; if(L.rear == p) L.rear = L.front; //else //修改 free(p); return 1; } int isempty(linkqueue L) { if(L.front == L.rear) return 1; else return -1; } int main() { int x; linkqueue s; initqueue(s); enqueue(s,3); printf("%d\n",s.rear->data); if(dequeue(s,x)) printf("%d\n",dequeue(s,x)); if(isempty(s)) printf("%d\n",isempty(s)); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 关于smbclient 库的使用
- ¥15 微信小程序协议怎么写
- ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
- ¥20 怎么用dlib库的算法识别小麦病虫害
- ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
- ¥15 java写代码遇到问题,求帮助
- ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
- ¥15 有了解d3和topogram.js库的吗?有偿请教
- ¥100 任意维数的K均值聚类
- ¥15 stamps做sbas-insar,时序沉降图怎么画