Linkedlistnext
Linkedlistnext
• A linked list data structure includes a series of connected nodes. Here, each node stores the
data and the address of the next node. A linked list is a linear data structure, in which the
elements are not stored at contiguous memory locations. The elements in a linked list are linked
using pointers. A linked list consists of nodes where each node contains a data field and a
reference (link) to the next node in the list.
CODE
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node
{
int info;
struct node *next;
};
void create()
{
struct node *last;
char ch;
do
{
newptr = getnode();
if (head == NULL)
head = newptr;
else
last->next = newptr;
last = newptr;
printf("Do you want to add more(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
printf("\nLinked List Created\n");
getch();
}
void insert()
{
int position;
printf("Enter the position to insert: ");
scanf("%d", &position);
newptr = getnode();
if (position == 1)
{
newptr->next = head;
head = newptr;
}
else
{
ptr = head;
for (int i = 1; i < position - 1 && ptr != NULL; i++)
{
ptr = ptr->next;
}
if (ptr == NULL)
{
printf("Invalid position\n");
}
else
{
newptr->next = ptr->next;
ptr->next = newptr;
}
}
void delete()
{
int position;
if (head == NULL)
{
printf("List is empty\n");
return;
}
if (ptr == NULL)
{
printf("Invalid position\n");
}
else
{
prev->next = ptr->next;
free(ptr);
}
}
void display()
{
ptr = head;
printf("The elements are\n");
while (ptr != NULL)
{
printf("%d ", ptr->info);
ptr = ptr->next;
}
}
int main()
{
int choice;
create();
while (1)
{
system("cls");
printf("Linked List\n1.Insert\n2.Delete\n3.Display\n4.Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete ();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
}
getch();
}
return 0;
}