我的任务是使用 C 给定两个简单规则重新排列矩阵的行。 1. 如果最后一列中的数字为正,则应将行移到顶部。2. 如果最后一列的数字为零,则该行应移至底部。
例如,如果我有 {{1,2,0},{4,5,-6},{7,8,9},{1,1,1}} 我会得到 {{1,1,1} ,{7,8,9},{4,5,-6},{1,2,0}}。
为此,我将矩阵实现为单链表,其中节点表示矩阵的行。然后我创建了一个名为“重新排列”的函数,它应该为我完成任务。除了第一行最后一列的数字为 0 时,我已经能够解决所有情况下的问题。那么我得到的只是 0。例如 {{0}{2}{3}} 或 { {1, 2, 0},{4, 5, 6}{7,8,9}} 都给出 0。如果有人可以查看我的代码并可能给我一些输入,我会非常高兴。这是我的代码:
typedef struct node node;
typedef struct list list;
struct list{
node* first;
node* last;
};
struct node{
int* data;
node* next;
};
list* newList(int* data);
static node* newNode(int* data);
list* newList(int* data);
void insertFirst(list* head, int* data);
void insertLast(list* head, int* data);
void rearrange(list* head,int rows, int cols);
void printList(list* head,int cols);
int main(){
int a[1] = {0};
int b[1] = {-2};
int c[1] = {-3};
//int d[1] = {-4}; // if we want more rows
//int e[1] = {-5};
//Create empty list
list* head = newList(a);
//Add rows
insertLast(head,b);
insertLast(head,c);
//insertLast(head,d);
//insertLast(head,e);
rearrange(head,3,1);
//Print all elements
printList(head,1);
return 0;
}
void printList(list* head,int cols){
int i;
node* currentEl = head->first;
while(currentEl != NULL) {
for(i=0;i<cols;i++){
printf("%d, ",currentEl->data[i]);
}
printf("\n");
currentEl = currentEl->next;
}
}
void rearrange(list* head,int rows,int cols){
head->last->next = head->first;
node* currentEl = head->last;
node* nextEl = head->first;
node* temp;
int count = 1;
while(count != rows+1){
int a = nextEl->data[cols-1];
temp = nextEl->next;
if(a>0 && count != 1){
nextEl->next = head->first;
head->first = nextEl;
currentEl->next = temp;
}else if(a==0 && head->first->data[cols-1] != 0){
head->last->next = nextEl;
head->last = nextEl;
nextEl->next = NULL;
currentEl->next = temp;
}else if(a==0 && head->first->data[cols-1] == 0){ // this needs to be changed
head->last->next = nextEl;
head->last = nextEl;
nextEl->next = NULL;
currentEl->next = temp;
}else {
currentEl = nextEl;
}
//nextEl = nextEl->next;
nextEl = currentEl->next;
if(count == 1){
head->last->next = NULL;
}
count++;
}
}
void insertFirst(list* head, int* data){
node* temp;
temp = newNode(data);
temp->next = head->first;
head->first = temp;
}
void insertLast(list* head, int* data){
node* temp;
temp = newNode(data);
head->last->next = temp;
head->last = temp;
}
static node* newNode(int* data){
node* new;
new = (node*)malloc(sizeof(node));
new->next = NULL;
new->data = data;
return new;
}
list* newList(int* data){
list* head;
node* node = newNode(data);
head = (list*)malloc(sizeof(list));
head->first = node;
head->last = node;
return head;
}