2017-03-09 107 views
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)); 

} 
+0

如果你不能管理打印的清单项目,然后是什么让你确定你的数据坐进列表中的第一个地方? –

+0

无论如何,你究竟看到了什么?编译错误?运行时错误?输出错误?提供细节。 –

+2

'char hold [100];'是本地自动变量。它不能在范围之外使用。 – BLUEPIXY

回答

1

pop返回指针到本地阵列失效的功能,因为后退出功能数组不活着。

当功能pop输出一些消息时,这也是一个坏主意。

只需重写功能通过以下方式

int pop(Stack s, char *item) 
{ 
    int success = !empty(s); 

    if (success) 
    { 
     strcpy(item, s->top->name); 

     NodePtr temp = s->top; 
     s->top = s->top->next; 
     free(temp); 
    } 

    return success; 
} 

,并调用它像

while (pop(s, n)) 
{ 
    puts(n); 
}