用C语言建立链表并输出链表内容。链表每个结点包括一个一元多项式的一项。 输入格式: 输入共n+1行,第一行是n的值,其余各行分别是每项的系数和指数。 输出格式: 输出共一行,依次用格式%dx^%d输出一项的值。指数为0的项、指数或系数为1的项与书写习惯相同。
时间: 2024-03-12 08:46:45 浏览: 11
好的,以下是用 C 语言实现链表建立和输出的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点
typedef struct ListNode {
int coef; // 系数
int exp; // 指数
struct ListNode* next; // 下一个结点指针
} ListNode;
// 建立链表
ListNode* createList(int n) {
ListNode* head = (ListNode*)malloc(sizeof(ListNode)); // 创建头结点
head->next = NULL; // 头结点指向空
ListNode* tail = head; // 初始化尾结点
// 依次输入每个结点的系数和指数
for (int i = 0; i < n; i++) {
int coef, exp;
scanf("%d %d", &coef, &exp);
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->coef = coef;
node->exp = exp;
node->next = NULL;
tail->next = node; // 将新结点接到尾结点后面
tail = node; // 更新尾结点
}
return head;
}
// 输出链表
void printList(ListNode* head) {
ListNode* node = head->next; // 从第一个结点开始输出
int isFirst = 1; // 是否是第一个输出的结点
while (node != NULL) {
// 输出符号和系数
if (node->coef > 0 && !isFirst) {
printf("+");
}
printf("%d", node->coef);
// 输出指数
if (node->exp > 1) {
printf("x^%d", node->exp);
} else if (node->exp == 1) {
printf("x");
}
node = node->next; // 指针指向下一个结点
isFirst = 0; // 不再是第一个输出的结点
}
}
int main() {
int n;
scanf("%d", &n);
ListNode* head = createList(n); // 建立链表
printList(head); // 输出链表
return 0;
}
```
可以通过以下输入进行测试:
```
3
2 3
-1 2
3 0
```
输出结果为:
```
2x^3-1x^2+3
```