|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想通过在终端输入一个多项式来讲系数和指数带进链表,由于输入长度未知,形式如:3x^4 + 2x^2 + x + 6这种,像系数为1和指数为0的就省略掉了,有没有什么办法能搞定这样的输入?
目前用的是scanf("%dx^%d",&p->coef,&p->expn);
但就只能正确输入所有格式为%dx^%d的,对于系数指数省略的就没办法一起识别,请大佬们帮帮忙!!谢谢!!!
附一下现在的代码,只实现了输入和(错误的)输出:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int status;
typedef int ElemType;
typedef struct NodeType
{
int coef;
int expn;
NodeType *next;
}*Polynomial, *LinkType;
void CreatePolyn(Polynomial &L) //创建多项式
{
int i;
int sign = 1;
Polynomial p,q;
L=(Polynomial)malloc(sizeof(NodeType));
L->next=NULL;
q=L;
char c;
p=(Polynomial)malloc(sizeof(NodeType));
scanf("%dx^%d",&p->coef,&p->expn);
p->coef *= sign;
q->next=p;
q=q->next;
c = getchar();
do{
p=(Polynomial)malloc(sizeof(NodeType));
c = getchar();
if(c == '+'){
sign = 1;
}else if(c == '-'){
sign = -1;
}
scanf("%dx^%d",&p->coef,&p->expn);
p->coef *= sign;
q->next=p;
q=q->next;
}while((c = getchar())!= '\n');
p->next=NULL;
}
//打印
void visit(ElemType coef, ElemType expn)
{
if(coef >= 0)
printf("+ %dx^%d ", abs(coef), expn);
else
printf("- %dx^%d ", abs(coef), expn);
}
//遍历
void PolynTraverse(Polynomial L, void(*visit)(ElemType, ElemType))
{
Polynomial p = L->next;
printf("%dx^%d ", p->coef, p->expn);
p = p->next;
while(p)
{
visit(p->coef, p->expn);
p = p->next;
}
printf("\n");
}
int main()
{
Polynomial L;
CreatePolyn(L);
PolynTraverse(L, visit);
return 0;
} |
|