“如果代码在struct中具有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);
}
输出: ./queue
您想要输入多少数据
3
输入要插入的数据:数据为
输入要插入的数据:a 数据是
输入要插入的数据:数据为
队列的数据是:
一
弹出的数据是
队列的数据是: 一个
“
答案 0 :(得分:1)
这可能不是唯一的问题,但是当您push
第一个元素时,您从未设置newnode->next = null
。
输出问题是因为您的队列包含\n
,a
和(空格)。
答案 1 :(得分:1)
您需要清除输入缓冲区。问题是因为在第一个输入(输入数量)之后按下的输入(\ n)被读取第一个输入字符。
阅读此link以了解如何清除输入缓冲区。它解决了输入问题,然后是\ n。
答案 2 :(得分:1)
作为快速修复(忽略安全性等),您可以在push函数中将scanf(“%c,&amp; d)更改为scanf(”\ n%c“,&amp; d)。这样,你将获取换行符和你要推送的实际字符。在scanf中使用整数格式将删除换行符,这就是它使用整数的原因。