【发布时间】:2017-03-09 20:50:35
【问题描述】:
这个程序应该以字符串的形式获取用户数据,并将其放入链表中。现在我能够将数据放入链接列表,但不确定为什么它不打印出来。
#include<stdio.h>
#include<stdlib.h>
// define the node of the stack
typedef struct node{
char name[100];
struct node *next;
}Node, *NodePtr;
// define the stack based on the linked list of nodes
typedef struct{
NodePtr top;
}StackType,*Stack;
// implement all the stack operations
Stack initStack(){
// allocate memory
Stack sp=(Stack)malloc(sizeof(StackType));
// set the top pointer to NULL
sp->top=NULL;
return sp;
}
int empty(Stack s){
return (s->top==NULL);
}
void push(Stack s, char *n){
NodePtr np= (NodePtr) malloc(sizeof(Node));
strcpy(np->name,n);
np->next=s->top;
s->top=np;
}
我认为某处的弹出功能有问题,但似乎无法解决
// pop the top element from the stack
char* pop(Stack s){
if(empty(s)){
printf("\n Error: Stack is empty");
return("err");
}
char hold[100];
strcpy(hold,s->top->name);
NodePtr temp=s->top;
s->top=s->top->next;
free(temp);
return hold;
}
int main(){
char n[100];
// create the stack
Stack s=initStack();
printf("Enter a list of names\n");
scanf("%s",&n);
while(strcmp(n,"end")!=0){
push(s,n);
scanf("%s",&n);
}
// print the stack
while(!empty(s))
printf("%s \n ", pop(s));
}
【问题讨论】:
-
如果您无法打印列表项,那么是什么确保您首先将数据放入列表中?
-
无论如何,你实际看到了什么?编译错误?运行时错误?输出不正确?提供详细信息。
-
char hold[100];是局部自动变量。不能在范围外使用。 -
不要在 typedef (
Stack,NodePtr) 后面隐藏指针性质。 -
放大 bluepixy 所说的内容,您使用的是
return hold,它返回一个变量的地址,该变量随后由于函数结束而立即过期。尽管最初是为 C++ 编写的,this question and the top answer are worth the read.
标签: c string linked-list