gpt4 book ai didi

c - C队列实现中的数据类型

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:10 24 4
gpt4 key购买 nike

“如果代码在结构中具有 int 数据类型但不适用于 struct 中的 char 数据类型,则该代码有效。”

#include    <stdio.h>     
#include <stdlib.h>
#define null 0

struct node{
char data;//works fine if it is int data
struct node *next;
};

void push(struct node **head)//add element to the queue
{
struct node *newnode,*p,*q;
char d;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nenter the data you want to insert:");
scanf("%c",&d);
newnode->data=d;
if(*head!=null)
{
p=*head;
while(p!=null)
{
q=p;
p=p->next;
}
q->next=newnode;
newnode->next=p;
}
else
*head=newnode;
printf("the data is %c\n",newnode->data);
}

void pop(struct node **head)//pops element of the queue
{
struct node *p;
if(*head!=null)
{
p=*head;
*head=p->next;
printf("The data popped is %c \n",p->data);
free(p);
}
else
printf("no data to pop\n");
}

void traverse(struct node **head)//displays the queue
{
struct node *k;
if(*head!=null)
{
k=*head;
printf("\nthe data of the queue is:\n");
while(k!=0)
{
printf("%c\n",k->data);
k=k->next;
}
}
else
printf("no data\n");
}

void main()
{
struct node *head=null;
int i,n;
printf("how many data you want to enter\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
push(&head);
}
traverse(&head);
pop(&head);
traverse(&head);
}

输出:./队列

你要输入多少数据

3

输入要插入的数据:数据为

输入要插入的数据:a数据是一个

输入要插入的数据:数据为

队列的数据是:

一个

弹出的数据是

队列的数据为:一个

最佳答案

这可能不是唯一的问题,但是当您push 第一个元素时,您从未设置newnode->next = null

您的输出出现问题是因为您的队列由 \na(空格)组成。

关于c - C队列实现中的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com