I'm working on a basic linked list programs. In this program I can insert elements at the beginning, at the middle (after one specific element) of the list and at the end. I also can delete a specific element or delete an element from the end of the list. I have all these four methods in the code.
Now I was trying in the main method to perform this operations in sequence:
- insert at the beginning
- insert at the middle
- delete a specific element
- delete an element from the list.
First I want to add 10 elements at the beginning of the list {50, 70, 80, 100, 77, 200, 44, 70, 6, 0}. Then I want to add 10 elements at the middle { 5, 20, 10 ,30 ,7 , 8, 2, 104, 1, 22} after the element 200. Then I want to add 10 elements at the end {40, 30, 20, 1, 7, 76, 4 , 0, 80, 2}. Then I want to delete a specific element 76 and then delete two elements at the end of the list.
So, I want the final list as {0, 6, 70, 44, 200, 22, 1, 104, 2, 8, 7, 30, 10, 20, 5, 77, 100, 80, 70, 50, 40, 30, 20, 1, 7, 4, 0}.
I don't know if it's a good way. Do you think the code in the main method is OK, the for parts particularly?
Main method:
int main()
{
printf("hi");
int i=0;
int listsize=10;
int arrBegining[] = {50,70, 80, 100, 77, 200, 44, 70, 6, 0};
int arrMiddle[] = {5, 20, 10, 30, 7, 8, 2, 104, 1, 22};
int arrEnd[] = {40, 30, 20, 1, 7, 76, 4 , 0, 80, 2};
for(i=0;i<listsize;i++){
insert_at_begning(arrBegining[i]);
}
for(i=0;i<listsize;i++){
insert_at_middle(arrMiddle[i], 200);
}
for(i=0;i<listsize;i++){
insert_at_end(arrEnd[i]);
}
for(i=0;i<listsize;i++){
delete_from_middle(76);
}
for(i=0;i<2;i++){
delete_from_end();
}
}
List operations:
void insert_at_begning(int value)
{
var=(struct node *)malloc(sizeof (struct node));
var->data=value;
if(head==NULL)
{
head=var;
head->next=NULL;
}
else
{
var->next=head;
head=var;
}
}
void insert_at_middle(int value, int loc)
{
struct node *var2,*temp;
var=(struct node *)malloc(sizeof (struct node));
var->data=value;
temp=head;
if(head==NULL)
{
head=var;
head->next=NULL;
}
else
{
while(temp->data!=loc)
{
temp=temp->next;
}
var2=temp->next;
temp->next=var;
var->next=var2;
}
}
int delete_from_middle(int value)
{
struct node *temp,*var;
temp=head;
while(temp!=NULL)
{
if(temp->data == value)
{
if(temp==head)
{
head=temp->next;
free(temp);
return 0;
}
else
{
var->next=temp->next;
free(temp);
return 0;
}
}
else
{
var=temp;
temp=temp->next;
}
}
printf("data deleted from list is %d",value);
}
int delete_from_end()
{
struct node *temp;
temp=head;
while(temp->next != NULL)
{
var=temp;
temp=temp->next;
}
if(temp ==head)
{
head=temp->next;
free(temp);
return 0;
}
printf("data deleted from list is %d",temp->data);
var->next=NULL;
free(temp);
return 0;
}