Dsa CH 3 Program
Dsa CH 3 Program
Step 1. Create a new node and assign the address to any node say ptr.
ELSE
Step 5. EXIT
Example SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node
{
int data;
struct node *link;
} *head;
void create(int);
void display();
void insert_end(int);
void insert_beg(int);
void insert_pos(int, int);
int delete_node(int);
main()
{
int choice, value, choice1, pos;
head=NULL;
while(1)
{
system ("cls");
printf("1. Create linked list:\n");
printf("2. Display linked list: \n");
printf("3. Insert Node in Linked List \n");
printf("4. Delete node \n");
printf("5. Exit");
switch(choice)
{
case 1: printf("Number of nodes:");
scanf("%d",&value);
create(value);
break;
case 2: display();
break;
case 3: system("cls");
printf("1. Insert node at beginning of list \n");
printf("2. Insert node at specific position \n");
printf("3. Insert node at the End of the List \n");
printf("Enter choice:");
scanf("%d", &choice1);
switch ( choice1 )
{
case 1: printf("Enter value for node :");
scanf("%d", &value);
insert_beg(value);
break;
case 4: break;
} break;
if(delete_node(value))
{
printf("%d deleted successfully\n",value);
getch();
}
else
{
printf("%d not found in the list\n",value);
getch();
}
}
break;
case 5: exit(1);
default: printf("Invalid Entry");
}
}
void create (int value)
{
system("cls");
struct node *temp;
temp = (struct node *) malloc ( sizeof (struct node));
if ( head == NULL)
{
temp->data = value;
temp->link = NULL;
head = temp;
}
printf("List created");
getch();
}
void display()
{
struct node *ptr;
ptr = head;
system("cls");
if (head == NULL)
{
printf("List is empty");
getch();
return;
}
printf("Linked List: \n");
while(ptr != NULL)
{
printf("%d ", ptr->info);
ptr = ptr->link;
}
printf("End_of_List");
getch();
}
void insert_end (int value)
{
struct node *ptr, *tempnode;
ptr = head;
while(1)
{
if (ptr->link != NULL)
ptr = ptr->link;
else
break; // otherwise break the infinite while loop
}
tempnode = (struct node *) malloc ( sizeof (struct node));
tempnode->data = value;
tempnode->link = NULL;
ptr->link = tempnode;
}
if (ptr->link == NULL)
{
insert_end(value);
}
else
{
tempnode = (struct node *) malloc ( sizeof (struct node) );
tempnode->data = value;
tempnode->link = ptr->link;
ptr->link = tempnode;
}
}
int delete_node(int value)
{
struct node *ptr, *prev;
ptr = head;
while (ptr != NULL)
{
if (ptr->data == value)
{
if (ptr == head)
{
head = ptr->link;
free(ptr);
return 1;
}
else
{
prev->link = ptr->link;
free(ptr);
return 1;
}
}
else
{
prev = ptr;
ptr = ptr->link;
}
}
return 0;
}
Important Questions