简体   繁体   中英

Adding to head of linked list

Student *addToHead(Student *node, int data) {
    Student *temp;
    temp = createNode(data);
    temp->nextPtr = node;
    return temp;
}

This code does not insert to the head of a linked list I have no clue why. I am not using a dummy node at the start of the linked list.

Here is my entire main function:

int main(void) {
    Student *test = initList();
    int searchTest = 0;

    test = addToHead(test, 3);
    test = addToHead(test, 2);
    test = addToHead(test, 1);
    test = addToTail(test, 4);
    test = addToTail(test, 5);

    printList(test);

    searchTest = searchAge(test, 4);
    printf("%d\n", searchTest);

    test = freeList(test);
}

Here is what is being output:

4
5
0
Free was successful

The tail is being correctly inserted but not the head.

Here is the code for tail

Student *addToTail(Student *node, int data) {
    Student *temp;
    temp = createNode(data);
    temp->age = data;

    if (node == NULL) {
        node = temp;
    } else {
        while (node->nextPtr != NULL) {
            node = node->nextPtr;
        }
        node->nextPtr = temp;
    }
    return node;
}

The problem is not the function addToHead . The problem is the function addToTail that you did not show.

It can look for example the following way

Student *addToTail(Student *node, int data){
        Student *temp = createNode(data);

        if ( node == NULL )
        {
            temp->nextPtr = node;
            node = temp;
        }
        else
        {
            Student *tail = node;
            while ( tail->nextPtr != NULL ) tail = tail->nextPtr;
            // Uncomment the line below if createNode does not set the data member nextPtr to NULL
            // temp->nextPtr = NULL
            tail->nextPtr = temp;
        }

        return node;
}

Edit: After you appended your answer with the definition of the function addToTail it is obvious that I was right saying that this function is wrong.

Within the function you are changing the head node

    while(node->nextPtr!=NULL){
        node=node->nextPtr;
    }

that you are returning from the function.

How do you call this function? The caller should do

head = addToHead(head, 3) 

for example.

What you want is more like

Student *addToHead(Student **head, int data) {
    Student *tmp = NULL;
    tmp = createNode(data);
    tmp->nextPtr = *head;
    *head = tmp;
    return tmp;
}

And then call it with

addToHead(&listHead, 42);

Or keep your version and call it with :

listHead = addToHead(listHead, 42);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM