In: Computer Science
Write the algorithm and code that creates an array of link lists where the user determines the number of rows and the number of nodes for each row.
Needs to be in C++ language.
IT IS DUE TONIGHT AT 11:59. HELP PLEASE
Two-Dimensional Array Example:
[0] |
[1] |
[2] |
[3] |
|
[0] |
2 |
4 |
6 |
8 |
[1] |
1 |
3 |
||
[2] |
8 |
4 |
6 |
|
[3] |
5 |
// C++ program to create an array of link list using 2D
array
#include <iostream>
using namespace std;
int main() {
int **linklist; // declare a 2D array representing
the link list of integers
int rows, *cols; // variables to store the number of
rows, and number of nodes in each row
// input the number of rows
cout<<"Enter the number of rows: ";
cin>>rows;
// create cols array of size rows to store the number
of columns in each row of linklist
cols = new int[rows];
// create linklist of size rows (containing int
pointer i.e array of ints)
linklist = new int*[rows];
// input the number of nodes in each row
cout<<"Enter the number of nodes for
"<<rows<<" rows"<<endl;
for(int i=0;i<rows;i++)
{
cout<<"Enter the nodes for
row-"<<(i+1)<<": ";
cin>>cols[i];
linklist[i] = new int[cols[i]]; //
create each entry of link list to be an array of size cols[i]
}
// input elements of the link list
cout<<"Enter the elements of the link list :
"<<endl;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols[i];j++)
{
cout<<"Row-"<<(i+1)<<"
Node-"<<(j+1)<<" : ";
cin>>linklist[i][j];
}
}
// display the link list
cout<<"Link List: "<<endl;
for(int i=0;i<rows;i++)
{
cout<<"["<<(i+1)<<"] : ";
for(int j=0;j<cols[i];j++)
{
cout<<linklist[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
//end of program
Output: