C Exercises: Convert a Singly Linked list into a array
C Singly Linked List : Exercise-12 with Solution
Write a C program that converts a singly linked list into an array and returns it.
Sample Solution:
C Code:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int num; //Data of the node
struct node *nextptr; //Address of the next node
}*stnode;
void createNodeList(int n);
void To_Array(struct node *head, int *array);
int main()
{
int n;
printf("\nLinked List: Convert a Singly Linked list into an array:\n");
printf("-------------------------------------------------------------\n");
printf("Input the number of nodes: ");
scanf("%d", &n);
createNodeList(n);
printf("\nReturn data entered in the list as an array:\n");
int arr[n];
To_Array(stnode, arr);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL;
tmp = stnode;
// Creating n nodes and adding to linked list
for(i=2; i<=n; i++)
{
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);
fnNode->num = num;
fnNode->nextptr = NULL;
tmp->nextptr = fnNode;
tmp = tmp->nextptr;
}
}
}
}
void To_Array(struct node *head, int *array) {
struct node *current = head;
int i = 0;
while (current != NULL) {
array[i] = current->num;
current = current->nextptr;
i++;
}
}
Sample Output:
Linked List: Convert a Singly Linked list into an array: ------------------------------------------------------------- Input the number of nodes: 4 Input data for node 1 : 10 Input data for node 2 : 20 Input data for node 3 : 30 Input data for node 4 : 40 Return data entered in the list as an array: 10 20 30 40
Flowchart :

C Programming Code Editor:
Previous: Convert a Singly Linked list into a string.
Next: Combine two sorted singly linked lists.
What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join