Conversion of a Linked List into Array

Conversion of a Linked List into Array

The conversion process involves creation of a linked list.  Then the list is read from the first node till the last node such that each node value is stored in an array and the node is removed by freeing its memory.  The array is then displayed as an output.

/*Conversion of a linked list into array*/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define MAX 10

typedef struct list
{int info;
list *next;
}list;

list *create()
{list *temp=(list *)malloc(sizeof(list));
if(temp==NULL)
{printf(“nMemory Allocation Error!”);
exit(1);
}
return temp;
}

list *makenode(int x)
{list *ptr=create();
ptr->info=x;
ptr->next=NULL;
return ptr;
}

list *insertend(list *head,int x)
{list *temp,*ptr=makenode(x);
if(head==NULL)
{head=ptr;
}
else
{temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=ptr;
}
return head;
}

void display(list *head)
{
list *temp;
if(head==NULL)
{printf(“List is empty.”);
return;
}
temp=head;
while(temp!=NULL)
{printf(“%d->”,temp->info);
temp=temp->next;
}
printf(“bb “);
}

int count(list *head)
{list *temp;
int ct=0;
temp=head;
while(temp!=NULL)
{ct++;
temp=temp->next;
}
return ct;
}

list *dispose(list *head)
{
list *temp;
while(head!=NULL)
{temp=head;
head=head->next;
free(temp);
}
return head;
}

list *convertlist_to_array(list *head,int arr[])
{int i=0;
list *temp=head;
while(temp!=NULL)
{arr[i++]=temp->info;
temp=temp->next;
}
head=dispose(head);
return head;
}

void main()
{
list *head=NULL;
int i,ch,num,size,arr[MAX]={0};
while(1)
{
clrscr();
printf(“nMenu”);
printf(“nn1. Create List”);
printf(“n2. Display List”);
printf(“n3. Convert List to Array”);
printf(“n4. Display Array”);
printf(“n5. Exit”);
printf(“nnEnter your choice?”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“Enter number?”);
scanf(“%d”,&num);
head=insertend(head,num);
break;
case 2:
display(head);
break;
case 3:
size=count(head);
printf(“nConverting List to Array…”);
head=convertlist_to_array(head,arr);
break;
case 4:
printf(“nDisplaying array elements: “);
for(i=0;i<size;i++)
printf(“%dt”,arr[i]);
printf(“bb “);
break;
case 5:
exit(0);
default:
printf(“Invalid choice!”);
}
getch();
}
}