Home > database >  Pointer in linked list
Pointer in linked list

Time:06-07

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  ;
    }
}

CodePudding user response:

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.

  • Related