Thursday 18 January 2018

C Program to understand some basic operations on linked list

#include<stdio.h>
#include<stdlib.h>
struct linkedlist
{
int data;
struct linkedlist *next;
};


int length(struct linkedlist *head){
int count=0;
struct linkedlist *head1=head;
while(head1)
{
count++;
head1=head1->next;
}
return count;

}

struct linkedlist* insert(struct linkedlist *head,int num,int pos)
{
struct linkedlist *node,*head1;

int i;
node=(struct linkedlist*)malloc(sizeof(struct linkedlist));

node->data=num;
node->next=NULL;
head1=head;
if(head==NULL && pos==1)
{
head=node;
printf("Element Inserted Successfully.\n");
}
else if(pos<length(head)+1){
if(pos==1){
node->next=head;
head=node;
}else{
for(head1=head,i=1;i<pos-1 && head1;i++,head1=head1->next);
node->next=head1->next;
head1->next=node;
}}
else if(pos>1 && pos<=length(head)+1)
{
for(head1=head,i=1;i<pos-1 && head1;i++,head1=head1->next);

head1->next=node;

printf("\nElement Inserted Successfully\n");
}

else printf("Error in Insertion\n");

return head;

}
void showlist(struct linkedlist *head){
struct linkedlist *head2=head;
if(head2==NULL)printf("\nLinked List is empty.");
else{
while(head2)
{
printf("  %d   ",head2->data);
head2=head2->next;
}
}

}

void reverse(struct linkedlist **head)
{
struct linkedlist *temp=NULL,*prev=NULL,*head1=*head;
//while(head1){prev=head1;head1=head1->next;new_head=head1;}
while(head1)
{
temp=head1->next;
head1->next=prev;
prev=head1;
head1=temp;

}*head=prev;
}
struct linkedlist* clone_list(struct linkedlist *head)
{

struct linkedlist *prev=NULL,*clonedLL=NULL,*clonedLLhead=NULL;
struct linkedlist *head1=head;
while(head1){
clonedLL=(struct linkedlist*)malloc(sizeof(struct linkedlist));
clonedLL->data=head1->data;
clonedLL->next=NULL;

showlist(head1);


clonedLLhead=clonedLL;
prev->next=clonedLL;
prev=clonedLL;
head1=head1->next;

}
return clonedLLhead;
}

int main()
{

struct linkedlist *cloneh=NULL,*head=NULL;

int i,num,pos,posdel;
do{
printf("Choose any operation:\n1.Insert an element.\n2.Delete an element \n3.View the Linked list.\n4.Reverse the lsit.\n5.Clone the list\n6.Exit\n");
scanf("%d",&i);
if(i==1)
{
printf("\nEnter the element to insert:");
scanf("%d",&num);
printf("Enter  a valid position:");
scanf("%d",&pos);
head=insert(head,num,pos);
}

if(i==2)
{
printf("\nEnter the position to delete:");
scanf("%d",&posdel);
//delete(head,posdel);
}
if(i==3)
{
showlist(head);
}
if(i==4)
{
reverse(&head);
}
if(i==5)
{
cloneh=clone_list(head);
printf("\nCloned Linked List:\n");
showlist(cloneh);
}
if(i==6)
break;
}while(1);
//free(head);
return 0;
}

No comments:

Post a Comment