Array of Linked Lists in C/C++
An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements that can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers, etc. Given below is the picture representation of an array.
an array is a container that can hold a fixed number of elements and these elements should be of the same type. Most of the data structures make use of arrays to implement their algorithms.
A linked list is a linear data structure consisting of nodes where each node contains a reference to the next node. To create a link list we need a pointer that points to the first node of the list.
Approach: To create an array of linked lists below are the main requirements:
- An array of pointers.
- For keeping the track of the above-created array of pointers then another pointer is needed that points to the first pointer of the array. This pointer is called pointer to pointer.
Below is the pictorial representation of the array of linked lists:
Below is the C++ program to implement the array of linked lists:
C++
#include <iostream>
using namespace std;
struct info {
int data;
info* next;
};
int main()
{
int size = 10;
info** head;
head = new info*[size];
for ( int i = 0; i < size; ++i) {
*(head + i) = NULL;
}
for ( int i = 0; i < size; ++i) {
info* prev = NULL;
int s = 4;
while (s--) {
info* n = new info;
n->data = i * s;
n->next = NULL;
if (*(head + i) == NULL) {
*(head + i) = n;
}
else {
prev->next = n;
}
prev = n;
}
}
for ( int i = 0; i < size; ++i) {
info* temp = *(head + i);
cout << i << "-->\t" ;
while (temp != NULL) {
cout << temp->data << " " ;
temp = temp->next;
}
cout << '\n' ;
}
return 0;
}
|
Output:
0--> 0 0 0 0
1--> 3 2 1 0
2--> 6 4 2 0
3--> 9 6 3 0
4--> 12 8 4 0
5--> 15 10 5 0
6--> 18 12 6 0
7--> 21 14 7 0
8--> 24 16 8 0
9--> 27 18 9 0
Time Complexity: O(size*4)
Here size is the number of rows of lists
Auxiliary Space: O(size*4)
The extra space is used to store the elements of the lists.
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...