PROGRAM MUST BE IN C! NOTE: Function should be in the C Function: lst_to_array *
ID: 3865265 • Letter: P
Question
PROGRAM MUST BE IN C!
NOTE: Function should be in the C
Function: lst_to_array
* Write a function that dynamically allocates an array of appropriate
* length and populates it with the elements of
* the given list (in the same order).
*
* Array is returned as a pointer to ElemType
* The length of the array (equal to the list length)
* is stored in *out_n
Sample invocation code:
LIST *lst;
ElemType *a;
int n;
lst = lst_create();
// bunch of operations on lst
a = lst_to_array(lst, &n);
Starting of the function
ElemType * lst_to_array(LIST *l, int *out_n) {
return NULL; // placeholder
}
Explanation / Answer
Function: lst_to_array
ElemType *a;
ElemType * lst_to_array(LIST *l, int *out_n) {
int i=0;
a=(int*)malloc(out_n*sizeof(int));
LIST *curr = l;
while(curr!=NULL){
a[i]=curr->val;
curr=curr->next;
}
return a;
}
Part B program
Function : lst_from_array:
void push(LIST *L,data){
LIST *curr =L;
if (curr->val==NULL){
curr->val=data;
curr->next=NULL;
}
else{
while(curr->next!=NULL){
curr=curr->next;
}
curr->next=malloc(sizeof(LIST));
curr->next->val=data;
curr->next->next=NULL;
}
}
lst=lst_create();
extern LIST *lst_from_array(ElemType a[], int n){
int i=0;
for(i=0;i<n;i++)
{
push(lst,a[i]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.