Data Structures Practical 12
Question 1
Write a function to insert a node at the beginning of a Singly Linked List.
linkedlist.c
C
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *start = NULL;
void insertAtBeginning(int data);
void displayList();
void main()
{
int choice, data;
char ch;
do
{
printf("\n--- SINGLY LINKED LIST OPERATIONS ---\n");
printf("1. Insert at Beginning\n");
printf("2. Display List\n");
printf("3. Exit\n");
printf("-------------------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter data to insert at beginning: ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 2:
displayList();
break;
case 3:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
printf("\nDo you want to continue(y/n)?");
ch = getch();
} while (ch == 'y' || ch == 'Y');
}
void insertAtBeginning(int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed!\n");
return;
}
newNode->data = data;
newNode->next = start;
start = newNode;
printf("%d inserted at the beginning.\n", data);
}
void displayList()
{
struct Node *ptr = start;
if (start == NULL)
{
printf("The list is empty.\n");
return;
}
printf("Linked List: ");
while (ptr != NULL)
{
printf("%d -> ", ptr->data);
ptr = ptr->next;
}
printf("NULL\n");
}
Output
