私のプログラムは、次のようにファイルの内容を読み取る必要があります。
name_of_program < Test.txt
Test.txt は整数の 2D 配列です (整数はスペースで区切られ、場合によっては複数の整数で、整数の行は EOL で区切られます)、長さと高さは不明です。それらをどのように判断しますか?リンクされたリストのノードに各行を整数の配列として格納する予定です。
編集:私のプログラムは大まかに次のようになります:
#include <stdio.h>
#include <stdlib.h>
struct node {
int *val; //stores the row
struct node *next;
};
struct node *addnode(int *val, struct node *next);
struct node *mergesort(struct node *head, int column); //column by which I'll sort it
struct node *merge(struct node *head_one, struct node *head_two, int column);
int main(int column) //number of column to sort by, should run like that "name_of_program column < Test.txt" in Unix systems
{
struct node *head;
struct node *current;
struct node *next;
head = NULL;
/* Reading from stdin line by line, writing it to list and linking nodes - I have only the last bit done */
head = mergesort(head, column);
/* Writing to stdout, row by row of sorted list, I can't do that without the previous bit */
for(current = head; current != NULL; current = next)
next = current->next, free(current);
return 0;
};
struct node *addnode(int *val, struct node *next)
{
struct node *tnode;
tnode = (struct node*)malloc(sizeof(*tnode));
if(tnode != NULL) {
tnode->val = val; //not sure about this line, would it write whole array, or just one element?
tnode->next = next;
};
return tnode;
}
struct node *mergesort(struct node *head, int column)
{
struct node *head_one;
struct node *head_two;
if((head == NULL) || (head->next == NULL))
return head;
head_one = head;
head_two = head->next;
while((head_two != NULL) && (head_two->next != NULL)) {
head = head->next;
head_two = head->next->next;
};
head_two = head->next;
head->next = NULL;
return merge(mergesort(head_one, column), mergesort(head_two, column), column);
}
struct node *merge(struct node *head_one, struct node *head_two, int column)
{
struct node *head_combined;
if(head_one == NULL)
return head_two;
if(head_two == NULL)
return head_one;
if(head_one->val[column] < head_two->val[column]) {
head_combined = head_one;
head_combined->next = merge(head_one->next, head_two, column);
} else {
head_combined = head_two;
head_combined->next = merge(head_one, head_two->next, column);
};
return head_combined;
}