Why do I get errors while trying to insert a new node to a list

时间:2015-10-30 21:43:25

标签: c++ list struct header stack

I have a header that declares a stack and a list. I am trying to add a node of stuck into the list but I fail to do so. Can someone help me figure out why this function doesn't work?

****both these codes are declerations in headers***

/* a link that contains a positive integer value*/
struct link
{
    int value;
    struct link *next;
};

typedef struct link link;

typedef struct
{
    link *head;
} linkedList;

/* a positive-integer value stack, with no size limit */
typedef struct stack
{
    int count;
    int maxSize;
    bool empty;
    linkedList* list;
} stack;

Now what I'm trying to do is this:

void add(linkedList *list, int newValue)
{
    linkedList* temp = list;


    while (temp->head)
    {
        temp->head = temp->head->next;
    }


    temp->head->next->value = newValue;   //<---- this line is making the error
}

// add new link in the beginning of list with newValue in it

1 个答案:

答案 0 :(得分:0)

In add, you're currently modifying temp->head to walk it through the list. temp is a local variable, but it points to the real linked list, so when you assign to temp->head, it's modifying the structure of the list itself.

I'd guess your real intent was something more like:

void add(linkedList *list, int newValue)
{
    link *temp = list->head;

    while (temp->next != nullptr)
        temp = temp->next;

    link *node = new node;
    node->next = nullptr;
    node->value = newValue;
    temp->next = node;
}

For a stack, however, you don't need (or want) to traverse the list before adding the new item.

void add(linkedList *list, int newValue) {
    link *node = new link;
    node->next = list->head;
    node->value = newValue;
    list->head = node;
}

As always, though, think twice about using a linked list (if you have any choice). At least in my experience, it's rarely a really useful data structure (especially in a case like this where you're storing small items--on a typical 64-bit implementation, each node will be a 32-bit int and a 64-bit pointer, so you're using twice as much space for pointers as for the data itself.