Linked lists in C++

前端 未结 4 2166
小鲜肉
小鲜肉 2020-12-18 05:25

I am trying to teach myself linked-lists with node structs and was hoping someone could help me with this. I would take input from the command line and it would make me a ne

4条回答
  •  自闭症患者
    2020-12-18 05:53

    You do not actually set the 'head' variable beyond NULL(head = ptr). You you actually lose your list from the get go. Try this:

    int n;
    NodePtr head, ptr;
    ptr = new Node;
    head = ptr;
    while (cin >> n){
        ptr->x = n;
        ptr->next = new Node;
        ptr = ptr->next;
    }
    

    You may then want to delete the last ptr->next and set it to 0 to save memory and avoid printing out an extra value.

提交回复
热议问题