1
該程序應該以字符串的形式獲取用戶數據並將其放入鏈接列表中。現在我可以將數據導入鏈表,但不知道爲什麼不打印出來。鏈接列表項不會打印
#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];'是本地自動變量。它不能在範圍之外使用。 – BLUEPIXY