【问题标题】:Linked list items wouldn't print链接列表项不会打印
【发布时间】: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


【解决方案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 );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2023-03-28
    相关资源
    最近更新 更多