OiO.lk Blog C++ How to insert data into Doubly Linked List using for loop in C
C++

How to insert data into Doubly Linked List using for loop in C


I made a Doubly Linked List, but instead of manually assigning the values (10, 20, 30) I want to make a for loop and put the data that way to make it efficient.
I did it in Singly Linked List but the same is not happening over here and only backward_traversing function works.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int value;
    struct Node *next_link;
    struct Node *prev_link;
} Node;

Node *create_node(int value)
{
    Node *new_node = malloc(sizeof(Node));
    new_node->value = value;
    new_node->next_link = NULL;
    new_node->prev_link = NULL;

    return new_node;
}

void forward_traversing(Node *head)
{
    Node *temp = head;

    while (temp != NULL)
    {
        printf("%d ", temp -> value);
        temp = temp->next_link;
    }
    printf("\n");
}

void backward_traversing(Node *tail)
{
    Node *temp = tail;

    while (temp != NULL)
    {
        printf("%d ", temp->value);
        temp = temp->prev_link;
    }
    printf("\n");
}

void show_first(Node *head)
{
    printf("%d \n", head->value);
}

void show_last(Node *tail)
{
    printf("%d \n", tail->value);
}

int main()
{
    Node *head, *temp, *tail;

    for (int i = 0; i <= 25; i++){
        temp = create_node(i);
        temp -> next_link = head;
        head = temp;
    }
    
    forward_traversing(head);
    backward_traversing(tail);
    show_first(head);
    show_last(tail);
    
    return 0;
}



You need to sign in to view this answers

Exit mobile version