1 - Singly Linked List
1 - Singly Linked List
Rakhi Mam, 3rd Sem
#include<stdio.h>
#include<stdlib.h>
typedef struct singly_list
{
int data;
struct singly_list *next;
}*SLL;
SLL getnode()
{
SLL new1;
new1 = malloc(sizeof(struct singly_list));
new1->next = NULL;
return new1;
}
SLL head = NULL, head_hash = NULL;
int main()
{
int ch;
char res;
SLL temp, new1, t1, t2, t3, prev, curr;
int p,w;
do
{
printf("\n1. creation\n2. display\n3.deletion\n4. Insertion\n5.sorting\n6.Reversing\n7.Print Prime Numbers\n8.Deleting Duplicate\n9.Find Middle element");
printf("\nEnter your choice:\t");
scanf("%d", &ch);
switch(ch)
{
case 1: //create
do
{
if(head == NULL)
{
head = getnode();
printf("\n Enter data of head node:\t");
scanf("%d",&head->data);
temp= head;
}
else
{
new1 = getnode();
printf("\n Enter data of new node:\t");
scanf("%d",&new1->data);
temp->next = new1;
temp = new1;
}
printf("\n do you want to add further data in the linked\t");
scanf(" %c",&res);
}while(res=='y');
break;
case 2://display
temp = head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp= temp->next;
}
printf("NULL");
break;
case 3: //deletion
printf("\nEnter position of node to be deleted:\t");
scanf("%d",&p);
temp =head;
w =1;
if(p==1) //deletion of first node
{
t1 = head;
head = temp->next;
free(t1);
}
else //deletion of last and any element except first
{
while(w<p-1)
{
temp = temp->next;
w++;
}
t1 = temp->next;
temp->next = temp->next->next;
free(t1);
}
break;
case 4: //insertionn of new node at any position
printf("\n Enter data of new node:\t");
new1 = getnode();
scanf("%d",&new1->data);
printf("\n\t\t\tEnter position of new node:\t");
scanf("%d",&p);
temp = head;
if(p==1)
{
new1->next= head;
head= new1;
}
else
{
while(p>2 && temp!=NULL)
{
temp = temp->next;
p--;
}
if(temp==NULL)
{
printf("\n\t\t\tINVALID position");
}
else
{
new1->next = temp->next;
temp->next =new1;
}
}
break;
case 6: //reversing of linked list
t1 = head;
t2= t1->next;
t3= t2->next;
t1->next=NULL;
do
{
t2->next =t1;
t1 = t2;
t2= t3;
t3= t3->next;
}while(t3!=NULL);
t2->next = t1;
head =t2;
break;
case 7:
temp = head;
while(temp!=NULL){
int c=0;
for(int i=2; i<temp->data; i++){
if(temp->data%i == 0){
c++;
break;
}
}
if(c==0){
printf("%d ", temp->data);
}
temp = temp->next;
}
break;
case 8: //delete duplicate
temp = head;
while(temp->next != NULL) {
t1 = temp;
while(t1 != NULL) {
if(t1->next != NULL && temp->data == t1->next->data) {
t2 = t1->next;
t1->next = t2->next;
free(t2);
}
t1 = t1->next;
}
temp = temp->next;
}
break;
case 9: //finding middle element
t1 = head;
t2 = head;
while(t2->next != NULL && t2->next->next != NULL){
t2 = t2->next->next;
t1 = t1->next;
}
printf("Middle element is %d", t1->data);
break;
default:
exit(0);
}
printf("\n Do you want to cont...");
scanf(" %c", &res);
}while(res=='y');
}

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home