tgcndr
tgcndr

Reputation: 15

Matrices with Linked List Implementation

I want to read matrices from the text file like:

2 3
52 7 100
90 36 90
22 35 62
56 51 23
58 98 74
86 32 45

First line indicates row and column size. Then I should read the data in the matrices and create a linked list with them. I also should find the sum matrix (it's not a problem). I wrote something, but I think it's not linked list implementation; it's just 2 dimensional array of structures. Do I do/think wrong? Can you give me any suggestions?

Upvotes: 0

Views: 785

Answers (1)

Dinesh
Dinesh

Reputation: 4559

I hope the following will help you get started

First, check out code at singly_linked_list. It has everything you need, nicely laid out and explained - struct NODE, create, prepend, and foreach/traversal. That page has a lot more to offer, actually.

Some pseudo code:

  1. get row, col // you already got it

  2. write a helper function NODE* process_line(line, col) which parses a line that has been read from file, tokenizes it, does atoi, and returns a linked-list that contains the row. It could return null to indicate errors, for example not enough values, non-integers, etc. Must free memory if you are returning null.

  3. you need 1 main linked list that stores your rows. Each node in this linked list will itself be a linked list that represents the row. (Another possible solution can be that each row is represented simply by an array of ints, of a known length).

  4. read file, line by line. Process the line to get the row in a suitable representation (a linked list, I have assumed). Push this into your main linked-list of rows as yet another node

  5. To compute sum, you need to traverse the outer linked-list. To process each row/node in this, you will need to traverse that row linked-list.

Iterating linked lists is easy

// modeling after
int list_foreach(NODE *node, int(*func)(void*))
{
   while(node) {
     if(func(node->data)!=0) return -1;
     node=node->next;
   }
   return 0;
}
// a more general purpose traversal which tracks state (a reduce-like op)
int list_traverse(NODE *node, void* state, int(*func)(void* state, void*data))
{
  while(node) {
    if (func(state, node->data)!=0) return -1; // something broke
    node=node->next;
  }
  return 0;
}

// Your actual summing functions

int sum_a_row(void* prev_state, void* data){
   int* psum = (int*)prev_state;
   *psum += (int)data;
   return 0; // a successful summing
}

int sum_matrix(void* prev_state, void* data) {
    NODE* row = (NODE*)data;
    int* psum = (int*)prev_state;
    int row_sum = 0;
    int error = list_traverse(row, &row_sum, sum_a_row);
    *psum += row_sum;
    return 0; // success in summing
}

int matrix_sum = 0;
int error = list_traverse(matrix_head_node, &matrix_sum, sum_matrix);

HTH. Forgive my coding style and any errors. You can simplify further if you assume a valid matrix when you reach summing.

Upvotes: 1

Related Questions