|
发表于 2023-12-15 18:04:12
|
显示全部楼层
要修改list_order函数,使得main函数打印的p1为(6,0),(3,1),(7,4),(8,9),可以按照以下步骤进行修改:#include <stdio.h>#include <stdlib.h>struct node_st { int coef; int exp; struct node_st* next;};struct node_st *list_create(int a[], int size);void list_display(struct node_st* p);struct node_st *list_order(struct node_st *p);void list_free(struct node_st *p);struct node_st *list_create(int a[], int size) { struct node_st *p = malloc(sizeof(struct node_st)); if (p == NULL) return NULL; p->next = NULL; struct node_st *cur = p; int i; for (i = 0; i < size; i++) { struct node_st *np = malloc(sizeof(struct node_st)); np->coef = a[i][0]; np->exp = a[i][1]; np->next = NULL; cur->next = np; cur = np; } return p;}void list_display(struct node_st* p) { struct node_st *cur = p->next; while (cur != NULL) { printf("(%d, %d) ", cur->coef, cur->exp); cur = cur->next; } printf("\n");}struct node_st *list_order(struct node_st *p) { struct node_st *prev, *cur, *temp; prev = p->next; cur = prev->next; while (cur != NULL) { if (cur->exp < prev->exp) { prev->next = cur->next; cur->next = p->next; p->next = cur; cur = prev->next; } else { prev = prev->next; cur = cur->next; } } return p;}void list_free(struct node_st *p) { struct node_st *cur, *next; cur = p->next; while (cur != NULL) { next = cur->next; free(cur); cur = next; } free(p);}int main() { int a[][2] = {{8, 9}, {3, 1}, {7, 4}, {6, 0}}; int b[][2] = {{4, 2}, {5, 3}, {-7, 4}, {10, 10}}; int size_a = sizeof(a) / sizeof(a[0]); int size_b = sizeof(b) / sizeof(b[0]); struct node_st *p1, *p2; p1 = list_create(a, size_a); p2 = list_create(b, size_b); p1 = list_order(p1); list_display(p1); list_display(p2); list_free(p1); list_free(p2); return 0;}
通过修改list_order函数中的排序逻辑,我们可以让p1按照(6,0),(3,1),(7,4),(8,9)的顺序打印出来。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|