Linked lists in C++

前端 未结 4 2167
小鲜肉
小鲜肉 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:36

    You aren't connecting the list. Every new item will have it's ->next NULL.

    You say ptr = ptr->next (which is NULL) but then the next iteration overwrites ptr with the newly allocated node. You need to rearrange your code to string the nodes together...

    One way of doing that is ptr->next = head makes your new node point to the old head. Then head = ptr to move the head to the new node. e.g.:

    To insert in the beginning (e.g. for a LIFO, last-in-first-out):

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

    To insert at the end (for a FIFO):

    while (cin >> n){
        if(!head) {
            head = new Node;
            ptr = head;
        }
        else
        {
            ptr->next = new Node;
            ptr = ptr->next;
        }
        ptr->next = NULL;
        ptr->x = n;
    }
    

提交回复
热议问题