0% found this document useful (0 votes)
23 views2 pages

Insertion at Beginning Edited

Isertion

Uploaded by

Shaliq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

Insertion at Beginning Edited

Isertion

Uploaded by

Shaliq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

INSERTION AT BEGINNING AND DISPLAY

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

typedef struct node {


int data;
struct node *next; // Change to struct node
} Node;

Node *head = NULL;


Node *tail = NULL;

int getChoice(char *[], int);


void insertion();
void display();

int main() {
int isExit = 0;
while (!isExit) {
char *choices[] = {"Insertion at beginning", "Display", "Exit"};
int choice = getChoice(choices, 3);
switch (choice) {
case 1:
insertion();
break;
case 2:
display();
break;
case 3:
isExit = 1;
break;
default:
printf("Invalid option.\n");
}
}
return 0;
}

void insertion() {
Node *newnode = (Node *) malloc(sizeof(Node)); // Use pointer
if (newnode == NULL) {
printf("Memory allocation failed.\n");
return;
}

printf("Enter data part of new node: ");


scanf("%d", &newnode->data);
newnode->next = head; // Insert at the beginning
head = newnode;
printf("Element inserted successfully\n");

// Update tail if the list was empty


if (tail == NULL) {
tail = newnode;
}
}

void display() {
Node *temp = head;
if (temp == NULL) {
printf("Linked List is empty\n");
} else {
printf("Linked List elements: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}

int getChoice(char *args[], int length) {


int choice;
printf("\nEnter choice:\n");
for (int i = 0; i < length; i++) {
printf("%d. %s\n", i + 1, args[i]);
}
printf(">>> ");
scanf("%d", &choice);
return choice <= length ? choice : 0; // Corrected here
}

You might also like