C语言建立链表并输出链表内容。链表每个结点包括一个一元多项式的一项。
时间: 2023-07-11 14:45:30 浏览: 202
好的,以下是一个示例代码,可以实现创建一元多项式的链表,并输出链表内容:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义链表结构体 */
struct Node {
int coef; // 系数
int expn; // 指数
struct Node *next; // 链接下一个结点的指针
};
/* 创建链表 */
struct Node *createList() {
struct Node *head, *tail, *node;
int c, e;
head = tail = (struct Node *)malloc(sizeof(struct Node)); // 创建头结点
tail->next = NULL;
printf("请输入一元多项式的系数和指数,以 0 0 结束:\n");
scanf("%d %d", &c, &e);
while (c != 0 || e != 0) {
node = (struct Node *)malloc(sizeof(struct Node)); // 创建新结点
node->coef = c;
node->expn = e;
node->next = NULL;
tail->next = node; // 将新结点链接到尾结点后面
tail = node; // 更新尾结点
scanf("%d %d", &c, &e);
}
return head;
}
/* 输出链表 */
void printList(struct Node *head) {
struct Node *p;
p = head->next; // 跳过头结点
while (p) {
printf("%dx^%d ", p->coef, p->expn);
p = p->next;
}
printf("\n");
}
/* 主函数 */
int main() {
struct Node *head;
head = createList();
printList(head);
return 0;
}
```
运行程序后,输入一元多项式的系数和指数,以 0 0 结束。比如输入 `3 2`、`-1 1`、`2 0`、`0 0`,表示多项式 $3x^2 - x + 2$,程序会输出 `3x^2 -x^1 2x^0`。
阅读全文
相关推荐
















