0

I have to make a doubly linked list in C. This list should work like stack, like I need to add new element to the begining. I created a head, and it has NULL. I use it for situations when my list is empty. But when the second iteration is running, my head is still NULL. This is my code:

#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#define LEN 1000
typedef struct list {
    char* string;
    struct list* prev, * next;
}LL;

LL* add(LL* head) {
    LL* temp = malloc(sizeof(LL));
    char buf[LEN];
    if (gets(buf) == '0')
        return 0;
    temp->string= (char*)malloc(strlen(buf) + 1);
    strcpy(temp->string, buf);
    if (head == NULL) {
        temp->next = NULL;
        temp->prev = NULL;
        head = temp;
        return head;
    }
    temp->prev = NULL;
    temp->next = head;
    head->prev = temp;
    head = temp;
    return head;

}
int main() {
    LL* head = NULL;
    int i = 0;
    while (i != 3) {
        add(head);
        i++;
    }
}

1 Answer 1

3

Well, your add function is returning the new head of the linked list. But you don’t do anything with the return value, so the head of the linked list is not being updated.

Instead of add(head), try head = add(head). This will update the head of your linked list to your newly created element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.