construct a linked list from 2d matrix in c++
C++ program for construct a linked list from 2d matrix. Here problem description and explanation.
// Include header file
#include <iostream>
#include <vector>
using namespace std;
// C++ program for
// Construct a linked list from 2D matrix
class LinkNode
{
public: int data;
LinkNode *next;
LinkNode *down;
LinkNode(int data)
{
this->data = data;
this->next = nullptr;
this->down = nullptr;
}
};
class DoublyLinkedList
{
public: LinkNode *head;
DoublyLinkedList()
{
this->head = nullptr;
}
void display()
{
if (this->head == nullptr)
{
cout << "Empty linked list";
}
else
{
LinkNode *front = this->head;
LinkNode *right = nullptr;
while (front != nullptr)
{
right = front;
while (right != nullptr)
{
cout << right->data << " ";
right = right->next;
}
cout << "\n";
// Visit to down node
front = front->down;
}
}
}
void insertData(vector < vector < int >> matrix,
int rows, int cols)
{
// Some auxiliary variables
LinkNode *levelHead = nullptr;
LinkNode *root = nullptr;
LinkNode *perv = nullptr;
int i = 0;
int j = 0;
// Add first row elements into result list
while (i < cols)
{
if (this->head == nullptr)
{
// Add first node
this->head = new LinkNode(matrix[0][i]);
levelHead = this->head;
}
else
{
// next head
levelHead->next = new LinkNode(matrix[0][i]);
levelHead = levelHead->next;
}
i++;
}
// Get first element
levelHead = this->head;
i = 1;
// Add all the bottom element of each column
while (i < rows)
{
root = nullptr;
perv = root;
while (j < cols)
{
levelHead->down = new LinkNode(matrix[i][j]);
if (root == nullptr)
{
root = levelHead->down;
perv = root;
}
else
{
perv->next = levelHead->down;
perv = levelHead->down;
}
levelHead = levelHead->next;
j++;
}
levelHead = root;
// reset col
j = 0;
// change row
i++;
}
}
};
int main()
{
DoublyLinkedList *dll = new DoublyLinkedList();
// Create 2D metrix
vector < vector < int >> matrix {
{
1 , 6 , 9 , 2 , -9
} , {
2 , 5 , -5 , 7 , 1
} , {
3 , 4 , 1 , 8 , 2
}
};
int rows = matrix.size();
int cols = matrix[0].size();
dll->insertData(matrix, rows, cols);
dll->display();
return 0;
}
Output
1 6 9 2 -9
2 5 -5 7 1
3 4 1 8 2
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment