c语言数据结构线性表-链表----一元多项式相加

C语言学习笔记数据结构记录二


c语言数据结构线性表-链表----一元多项式相加


  • 作业 :用链表创建两个一元多项式,并实现两个多项式相加
  • 功能实现 尾插法创建单链表 两式相加 打印
#include
#include
#define length sizeof(struct Polynode)

//定义节点结构
typedef struct Polynode
{
	int coef;
	int exp;
	struct Polynode * next;  /*建立next指针*/
} Polynode, * PolyList;

// 初始化
void InitList(PolyList L)   /*注意PolyList结构指针类型*/
{
	(L) = (PolyList)malloc(sizeof(length));     /* L相当于链表头指针变量  */
	(L) -> next = NULL;
}

//尾插法
PolyList creat_list(PolyList L)
{
	Polynode *head,*rear,*s;
	int coef,exp;
	// head = (Polynode)malloc(sizeof(Polynode));  //建立头结点
	rear = L;  //建立尾节点
	printf("请输入系数和指数\n");
	scanf("%d,%d",&coef,&exp);  //输入数据
	while(coef != 0)
	{
		s = (PolyList)malloc(sizeof(Polynode));  //申请新节点
		s -> coef = coef;
		s -> exp = exp;
		rear -> next = s; //上一个尾节点指向新插入的节点
		rear = s;   //新插入节点位置给尾节点
		printf("请输入系数和指数\n");
		scanf("%d,%d",&coef,&exp);  //输入数据      
	}
	rear -> next = NULL;
	return(head);
}

//相加
void PolyAdd(PolyList L1,PolyList L2)
{
	Polynode *p,*q,*tail,*temp;
	int sum;
	p = L1 -> next;
	q = L2 -> next;
	tail = L1;

	while(p!=NULL && q!=NULL)
	{
		if(p -> exp < q -> exp)
		{
			tail -> next = p;
			tail = p;
			p = p -> next;
		}
		else if (p -> exp == q -> exp)
		{
			sum = p -> coef + q -> coef;
			if (sum != 0)
			{
				p -> coef = sum;
				tail -> next = p;
				tail = p;
				p = p -> next;
				temp = q;
				free(temp);
				q = q -> next;
			}
			else
			{
				temp = p ; p = p -> next; free(temp);
				temp = q ; q = q -> next; free(temp);
			}
		}

		else
		{

			tail -> next = q;
			tail = p;
			q = q -> next;
		}

		if (p!= NULL) tail -> next = p;
		else tail -> next = q;
	}
	// return(tail);
}


//打印
void print_list(PolyList L)
{
	Polynode *p;
	if (L -> next != NULL)
	{
		p = L -> next;  //定义首节点
		printf("F(x) = ");
		while(p != NULL)
			{
				
				printf("%dX^%d",p -> coef,p -> exp);
				if (p ->next != NULL) printf("+");
				else break;  //因为是以输出0结尾的  所以尾节点不要输出
				p = p -> next;
			}
		
	}
	else
	{   
		printf("此为空表!\n");
	}
}


int main()
{
	void InitList(PolyList *L) ;
	PolyList creat_list(PolyList L);
	void PolyAdd(PolyList L1,PolyList L2);
	void print_list(PolyList L);
	Polynode A,B;
	PolyList L1,L2;
	L1 = &A;L2 = &B;
	printf("\n方程一...\n");
	creat_list(L1);
	print_list(L1);
	printf("\n方程二...\n");
	creat_list(L2);
	print_list(L2);
	PolyAdd(L1,L2);
	printf("\n相加之后...\n");
	print_list(L1);
}

你可能感兴趣的:(笔记)