#include <stdio.h>
#include <stdlib.h>
#define SIZE 3
// Define the structure for a node
typedef struct Node {
int data;
struct Node* right;
struct Node* down;
} Node;
// Function to create a new node
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = value;
newNode->right = NULL;
newNode->down = NULL;
return newNode;
}
// Function to construct a 2D linked list from a 2D matrix
Node* constructLinkedList(int matrix[][SIZE], int rows, int cols) {
Node* head = NULL;
Node* prevRow[SIZE] = {NULL}; // Array to track previous row nodes
for (int i = 0; i < rows; i++) {
Node* rowHead = NULL;
Node* prevNode = NULL;
for (int j = 0; j < cols; j++) {
Node* newNode = createNode(matrix[i][j]);
if (!rowHead) rowHead = newNode; // Set the head of the current row
if (prevNode) prevNode->right = newNode; // Link the previous node in the row
if (prevRow[j]) prevRow[j]->down = newNode; // Link the node above in the column
prevNode = newNode;
prevRow[j] = newNode; // Update the previous row tracker
}
if (!head) head = rowHead; // Set the head of the entire linked list
}
return head;
}
// Function to print the 2D linked list
void printLinkedList(Node* head) {
Node* row = head;
while (row) {
Node* col = row;
while (col) {
printf("%d ", col->data);
col = col->right;
}
printf("\n");
row = row->down;
}
}
// Function to free the 2D linked list
void freeLinkedList(Node* head) {
Node* row = head;
while (row) {
Node* col = row;
while (col) {
Node* temp = col;
col = col->right;
free(temp);
}
row = row->down;
}
}
int main() {
int matrix[SIZE][SIZE] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Node* head = constructLinkedList(matrix, SIZE, SIZE);
printLinkedList(head);
freeLinkedList(head); // Clean up memory
return 0;
}
/*
run:
1 2 3
4 5 6
7 8 9
*/