DS Practical Slip 5 Q A

C Program to Implement Doubly Linked List (Create and Display)

A Doubly Linked List is a linear data structure where each node contains data, a pointer to the next node, and a pointer to the previous node. In this program, we will implement Create and Display operations in a simple student-friendly way.


šŸ“ Problem Statement

Q1. A) Write a C program to implement a doubly linked list with Create and Display operation.


šŸ’” Logic (Simple Steps)

šŸ”¹ Create Operation

  1. Define a structure with:
    • data
    • prev pointer
    • next pointer
  2. For each new node:
    • Allocate memory using malloc().
    • If list is empty → make it head.
    • Otherwise:
      • Move to last node.
      • Link last node’s next to new node.
      • Set new node’s prev to last node.

šŸ”¹ Display Operation

  1. Start from head.
  2. Traverse using next pointer.
  3. Print each node’s data.

šŸ’» Source Code (Simple Version)

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

struct node
{
    int data;
    struct node *prev;
    struct node *next;
};

int main()
{
    struct node *head = NULL, *newnode, *temp;
    int n, i, value;

    printf("Enter number of nodes: ");
    scanf("%d", &n);

    for(i = 0; i < n; i++)
    {
        printf("Enter value: ");
        scanf("%d", &value);

        newnode = (struct node*)malloc(sizeof(struct node));
        newnode->data = value;
        newnode->prev = NULL;
        newnode->next = NULL;

        if(head == NULL)
        {
            head = newnode;
        }
        else
        {
            temp = head;
            while(temp->next != NULL)
            {
                temp = temp->next;
            }

            temp->next = newnode;
            newnode->prev = temp;
        }
    }

    printf("Doubly Linked List elements are:\n");
    temp = head;
    while(temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }

    return 0;
}

šŸ–„ļø Sample Output

Enter number of nodes: 3
Enter value: 10
Enter value: 20
Enter value: 30
Doubly Linked List elements are:
10 20 30

šŸŽ“ Viva Questions with Answers

1. What is a doubly linked list?

A doubly linked list is a list where each node contains two pointers: one to the next node and one to the previous node.

2. What are the advantages of a doubly linked list?

It allows traversal in both forward and backward directions.

3. What does the prev pointer store?

It stores the address of the previous node.

4. What is the first node’s prev value?

It is NULL.

5. What function is used for dynamic memory allocation?

malloc() is used.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top