关于c 一元多项式链表的建立和打印

#include <stdio.h>
#include <stdlib.h>

struct Node
{
	int coefficient; // 系数
	int exponent;    // 指数。
	struct Node *Next;
};

typedef struct Node *PtrToNode;

typedef PtrToNode Polynomial;


void CreatList(PtrToNode *List)                                  //创建链表
{
	PtrToNode r;
	PtrToNode s;
	int n;
	*List = (PtrToNode )malloc(sizeof(PtrToNode));
	r = *List;
	printf("please input terms\n");
	scanf("%d", &n);
	printf("please coefficients and exponents\n");
	while (n--)
	{
		s = (PtrToNode)malloc(sizeof(PtrToNode));
		scanf("%d", &s->coefficient);
		scanf("%d", &s->exponent);
		r->Next = s;
		r = s;		
	}
	r->Next = NULL;
}

int exp1(int y, int x)                                // 指数函数的值
{
	int result = 1;
	while(x--)
	{
		result  = result * y;
	}
	return result;
}
int ResultList(PtrToNode *List)                      // 链表的结果
{
	PtrToNode r;
	r = (*List)->Next;
	int result = 0;
	int y;
	printf("Please input value of y=\n");
	scanf("%d", &y);
	while (r != NULL)
	{
		result += (r->coefficient)*exp1(y, r->exponent);
		r = r->Next;
	}
	
	return result;
	
	
	printf("\n");
}
void PrintList(PtrToNode *List)                         //打印链表。
{
	PtrToNode r;
	
	r = (*List)->Next;
	while (r != NULL)
	{
		printf("%dy^%d", r->coefficient, r->exponent);
		if (r->Next != NULL)
		{
			printf(" + ");
		}
		r = r->Next;
	}
	printf("\n");
}

int main(void)
{

	PtrToNode List = NULL;	
	CreatList(&List);             //链表指针的地址。
	PrintList(&List);
	printf("the result is %d\n", ResultList(&List));
	return 0;
}



我认为创建一元多项式并不难,关键在于怎么把链表的指针传进去。这需要涉及到指针参数传递的一些知识。下面附带个一个测试程序。把指针参数作为参数传给函数。


#include <stdio.h>
#include <stdlib.h>

void fn(int **p1)
{
    int *p2 = (int *)malloc(sizeof(int));
    *p2=10;
     *p1=p2;
}
void main()
{
   // int *p = (int *)malloc(sizeof(int));
   int *p;
    fn(&p);
    printf("d\n", *p);
}
希望对大家都有所帮助。有什么需要探讨的。请留言。










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_807315755

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值