我试图在堆栈中创建一个推入函数,该函数接受一个字符串并将每个字符存储在单独的节点中,但是当我运行程序并输入字符串时,它仅存储第一个字母。以下是用于该功能的代码:
void push(char *word){
struct stack *newNode = malloc(sizeof(char *));
if(newNode == NULL){
printf("unable to push to stack");
}else{
strcpy(newNode -> word,word);
newNode -> next = head;
head = newNode;
}
printf("Inserted in stack\n");
}
int main(){
int choice;
char str[100];
printf("Enter a string: ");
gets(str);
while(1)
{
printf("******** Menu ********\n");
printf(" 1. Push\n 2. Display\n 3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
push(str);
break;
case 2:
display();
break;
case 3:
printf("\nProgram Exited\n");
exit(0);
break;
default:
printf("Incorrect selection!\n");
}
void display(){
struct stack* newNode;
if(head == NULL){
printf("\nStack is Empty!!!\n");
}else{
newNode = head;
while(newNode != NULL){
printf("%c--->", newNode -> word);
newNode = newNode -> next;
}
}
}
}
答案 0 :(得分:0)
这里有很多问题,首先是它不是完整的代码集。您不见了:
此外,您还遇到以下代码错误:
malloc,而不是链接列表中节点的正确大小,即 struct stack
printf格式%c,一个字符,当您要打印存储在节点中的字符串时,即%s
最后,您正在使用以下不良做法:
但是,填写缺失的部分并纠正我提到的错误,以及设置代码的可读性,我可以运行它并验证 push()函数是否确实能够正确插入链接列表的开头。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_MAX 100
struct stack
{
char word[STRING_MAX];
struct stack *next;
};
struct stack *head = NULL;
void display();
void push(char *word)
{
struct stack *newNode = malloc(sizeof(struct stack));
if(newNode == NULL)
{
printf("unable to push to stack\n");
}
else
{
strcpy(newNode -> word,word);
newNode -> next = head;
head = newNode;
}
printf("Inserted in stack\n");
}
int main()
{
int choice;
char str[STRING_MAX];
printf("Enter a string: ");
gets(str);
while(1)
{
printf("******** Menu ********\n");
printf(" 1. Push\n 2. Display\n 3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
push(str);
break;
case 2:
display();
break;
case 3:
printf("\nProgram Exited\n");
exit(0);
break;
default:
printf("Incorrect selection!\n");
break;
}
}
display();
return 0;
}
void display()
{
struct stack* newNode;
if(head == NULL)
{
printf("\nStack is Empty!!!\n");
}
else
{
newNode = head;
while(newNode != NULL)
{
printf("%s--->", newNode -> word);
newNode = newNode -> next;
}
printf("\n");
}
}