DS Practical Slip 4 Q B

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

A Singly Linked List is a linear data structure where each node contains data and a pointer to the next node. In this program, we will implement two basic operations:

  • Create a linked list
  • Display the linked list

📝 Problem Statement

B) Write a C program to implement a singly linked list with Create and Display operation.


💡 Logic (Simple Student-Friendly Steps)

🔹 Create Operation

  1. Define a structure with:
    • data
    • next pointer
  2. For each new value:
    • Create a new node.
    • If list is empty → make it head.
    • Otherwise → attach it at the end.

🔹 Display Operation

  1. Start from head.
  2. Traverse until NULL.
  3. Print each node’s data.

💻 Source Code (Simple Version)

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

struct node
{
    int data;
    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->next = NULL;

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

    printf("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: 4
Enter value: 10
Enter value: 20
Enter value: 30
Enter value: 40
Linked list elements are:
10 20 30 40

🎓 Viva Questions with Answers

1. What is a singly linked list?

A singly linked list is a linear data structure where each node points to the next node only.

2. What does a node contain?

It contains data and a pointer to the next node.

3. What is head in a linked list?

Head is a pointer that stores the address of the first node.

4. What is the last node’s next value?

It is NULL.

5. What is dynamic memory allocation used here?

malloc() is used to allocate memory dynamically.

Spread the love

Leave a Comment

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

Scroll to Top