kunkundebasketba 2022-08-01 16:30 采纳率: 64.3%
浏览 46
已结题

这是本人对队列链式结构综合运用写的一段代码,但是输出入队的data值是乱码,不是入队的值,请问为什么会这样的呢?

这是本人对队列链式结构综合运用写的一段代码,但是输出入队的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));
}

  • 写回答

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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 8月12日
  • 已采纳回答 8月4日
  • 创建了问题 8月1日

悬赏问题

  • ¥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,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?