求助大佬们
c语言吧
全部回复
仅看楼主
level 7
GHFRTDRT 楼主
新年快乐,各位大佬,我想创建一个链表然后输入多项式,x为常数,y为幂,然后根据幂的大小进行链表插入,但是不懂为什么输出不了,请教大佬,代码放评论区了,谢谢大佬[太开心]
2024年02月10日 04点02分 1
level 7
GHFRTDRT 楼主
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node* ptr;
struct node
{
int coe;
int exp;
ptr next;
};
ptr create(void);
void add(ptr s, int x, int y);
int* arr(ptr s, int x, int y);
void print(ptr s);
int main(void)
{
ptr s1;
s1 = create();
add(s1, 1, 2);
add(s1, 3, 2);
add(s1, 1, 3);
add(s1, 1, 0);
print(s1);
return 0;
}
ptr create(void)
{
ptr s;
s = (ptr)malloc(sizeof(struct node));
if (s == NULL)
{
printf("create fail\n");
return 0;
}
s->next = NULL;
return s;
}
int num(ptr s)
{
int NUM;
s = s->next;
while (s != NULL)
{
NUM++;
}
return NUM;
}
int* arr(ptr s, int x ,int y)
{
int* ar;
int NUM;
NUM = num(s);
ar = (int*)malloc(sizeof(int) * NUM);
for (int i = 0; i < NUM; i++)
{
ar[i] = y;
}
return ar;
}
void add(ptr s, int x, int y)
{
ptr value;
value = (ptr)malloc(sizeof(struct node));
if (s->next == NULL)
{
value->next = s->next;
s->next = value;
value->coe = x;
value->exp = y;
}
else
{
int* ar;
int arn;
int index;
arn = num(s);
ar = arr(s, x, y);
for (int i = 0; i < arn; i++)
{
if (y == ar[i])//等于
{
index = 0;
s = s->next;
while (index < i)
{
s = s->next;
index++;
}
s->coe = s->coe + x;
break;
}
else if(y < ar[i])//小于
{
index = 0;
s= s->next;
while (index < i)
{
s= s->next;
index++;
}
value->next = s->next;
s->next = value;
value->coe = x;
value->exp = y;
break;
}
else//大于
{
value->next = s->next;
s->next = value;
value->coe = x;
value->exp = y;
break;
}
}
}
}
void print(ptr s)
{
s = s->next;
printf("%d^%d ", s->coe, s->exp);
while (s != NULL)
{
printf("+");
printf(" %dX^%d", s->coe, s->exp);
s = s->next;
}
}
2024年02月10日 05点02分 3
num函数里面死循环了,记得把s指向next
2024年02月10日 07点02分
好的,谢谢大佬,忘了,写太急了一下没注意
2024年02月10日 13点02分
level 6
返回这个值是程序崩溃了
2024年02月10日 06点02分 4
level 6
能发代码截图吗,我怎么找了半天没找着主函数
2024年02月10日 06点02分 5
那个int main(void)就是主函数
2024年02月10日 06点02分
我打错了吗?
2024年02月10日 07点02分
@GHFRTDRT 只是我眼瞎[喷]
2024年02月10日 07点02分
@GHFRTDRT create函数执行完应该是被回收了,ptr变空指针了,把create改成node类型,用一个node类型的变量接create的返回值
2024年02月10日 07点02分
level 1
为啥你们都不喜欢写注释[呵呵]
2024年02月10日 07点02分 6
sorrysorry,自己写题一直没什么习惯写[泪]
2024年02月10日 13点02分
level 3
你这个每次生成不是必定y=ar?逻辑有问题吧,而且NUM没有初始化为0
2024年02月10日 07点02分 7
我是想先判断这个链表里是否有元素,如果没有,直接添加链表,如果有,则先判断插入的数值大小,然后在找地方插入
2024年02月10日 13点02分
大佬我这个逻辑哪里有问题吗?[小乖]
2024年02月10日 13点02分
我懂了大佬,是我那个数组每次只会生成一个元素,谢谢大佬
2024年02月10日 16点02分
level 9
你这注释。。。[喷]
2024年02月10日 10点02分 8
sorrysorry
2024年02月10日 13点02分
level 9
自定义函数 int num(ptr s) ; 变量NUM 没有初始化0;
2024年02月10日 10点02分 9
谢谢大佬[真棒]
2024年02月10日 13点02分
1