我一直在尝试在控制台中打印字符堆栈的实际大小,但是它不允许我打印字符数量和数据大小一样的字符。有人可以帮我理解这个主意吗?我已经创建了具有推,弹出和显示功能的节点来显示结果。字符大小由用户定义,以便他们可以打印任意数量的字符。
#include <stdio.h>
#include <stdlib.h>
struct node{
char data;
struct node* next;
};
void init(struct node* head){
head=NULL;
}
//push an element into the stack
struct node* push(struct node* head, int data){
struct node* temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL){
exit(0);
}
temp->data=data;
temp->next=head;
head=temp;
return head;
}
//to pop an element from the stack
struct node* pop(struct node *head, int *element){
struct node* temp=head;
*element=head->data;
head=head->next;
free(temp);
return head;
}
//to display the element from the stack we transverse the stack element from the first element to NULL
void display(struct node* head){
struct node* current;
current=head;
if(current!=NULL){
printf("Stack: ");
do{
printf("%c", current->data);
current=current->next;
}
while(current!=NULL);
printf("\n");
}
else{
printf("the stack is empty\n");
}
}
int main(int argc, char *argv[]) {
struct node* head=NULL;
char letter;
int size;
int counter=0;
printf("Enter the number of stack elements");
scanf("%d", &size);
printf("---Push elements into the linked Stack---\n");
init(head);
while(counter<size){
printf ("Enter a number to push into the stack:");
scanf("%c",&letter);
head = push(head,letter);
display(head);
counter++;
}enter code here
printf("--- Pop elements from the linked stack --- \n");
while(empty(head) == 0)
{
head = pop(head,&letter);
printf("Pop %c from stack\n",letter);
display(head);
}
return 0;
}
答案 0 :(得分:0)
您可能已被输入%c
指定符所困扰。它很高兴从输入流中返回任何字符,包括空格或换行符,而所有其他说明符都跳过非打印字符。这意味着例如您可能具有以下行为:
,然后...您的堆栈中充满了8个字符:'1'
,'\n'
,'2'
,'\n'
,'3'
,{{1} },'\n'
,'4'
!
解决方法:只需在一行中回答八个字符:12345678 Enter ,输入后将显示提示,但至少您可以用所需的内容填充堆栈。
解决方案:更改代码以过滤掉换行符。您还可以考虑将'\n'
替换为scanf("%c", &letter);
说明符:
%1s
您应该测试输入函数(char dummy[2]; /* provide a place for the null */
...
scanf("%1s", dummy); /* will skip over blanks and new lines */
letter = dummy[0];
)的返回值,以确保没有发生IO问题...