I have more experience with linked lists after gaining practice and support from SO, given my last few questions. Essentially, I am now following an algorithm that will convert an array to a singly linked list.
Algorithm: CONVERT (A, N, HEAD)
1. Set HEAD = NULL
2. Repeat steps 3 to 8 while N ≠ -1
3. Allocated memory for NEW node
4. IF NEW = NULL then Print: “Memory not Available” and Return
5. Set NEW→DATA = A[N-1]
6. Set NEW→LINK = HEAD
7. Set HEAD = NEW
8. Set N = N - 1
[End of loop]
9. Return
I have attempted creating the code for this, however, after printing out the node carrying the data, I get a bunch of zeros. I know that with an array, if I assign a large size to the array and do not fill all values in, then these are assigned 0. However, this is not the case for my example.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int DATA;
struct node* LINK;
} node;
void convert(int A[], int N, node* head){
head = NULL;
while(N != -1){
node* new;
new = (node*)malloc(sizeof(node));
if (new == NULL){
printf("Memory not available");
return;
}
printf("%i", new->DATA);
new->DATA = A[N-1];
new->LINK = head;
head = new;
N--;
}
return;
}
int main(){
int arr[10] = {0, 1, 2, 3, 4};
int size = sizeof(arr)/sizeof(arr[0]);
node* former;
former = (node*)malloc(sizeof(node));
convert(arr, size, former);
return 0;
}
Would print out the following:
00000000000%
How do I convert the array values to the singly linked list, what might I be missing?
printf("%i", new->DATA);should be afternew->DATA = A[N-1];, you are printing uninitialized values currently.head = NULL;headfromconvertand replaceformer = malloc(...)withformer = convert(...)