C-数据结构-单向链表(示例)

多项式合并

poly.c

c 复制代码
#include<stdio.h>
#include<stdlib.h>


struct node_st
{
	int coef;
	int exp;
	struct node_st *next;//自引用结构的指针

};

struct node_st *poly_create(int a[][2],int n)
{
	int i;
	struct node_st *me;//me是头节点,最好不动
	struct node_st *newnode,*cur;
	me = malloc(sizeof(*me));
	if(me == NULL)
		return NULL;
	me->next = NULL;
	cur = me;
	
	for(i = 0 ; i < n; i++)
	{
		newnode = malloc(sizeof(*newnode));
		if(newnode == NULL)
			return NULL;
		newnode->coef = a[i][0];
		newnode->exp = a[i][1];
		newnode->next = NULL;
		
		cur->next = newnode;
		cur = newnode;
	}
	
	return me;	
}
void poly_show(struct node_st *me)
{
	struct node_st *cur;
	for(cur = me->next;cur !=NULL;cur->next)
	{
		printf("(%d %d)",cur->coef,cur->exp);
	}
	printf("\n");
}
void poly_union(struct node_st *p1,struct node_st *p2)
{
	struct node_st *p,*q,*r;
	p = p1->next;
	q = p2->next;
	r = p1;
	while(p && q)
	{
		if(p->exp < q->exp)
		{
			r->next = p;
			r = p;
			p = p->next;
		}
		else if(p->exp > q->exp)
			{
				r->next = q;
				r =q;
				q= q->next;
			}
			else
			{
				p->coef += q->coef;
				if(p->coef)
				{
					r->next = p; 
					r = p;
					//p = p->next;可省略
					//q = q->next;可省略
				}
				p = p->next;
				q = q->next;
			}
	}
	if(p =NULL)
		r->next=q;
	else
		r->next=p;

}

int main()
{
	int a[][2] = {{5,0},{2,1},{8,8},{3,16}};
	int b[][2] = {{6,1},{16,6},{-8,8}};

	struct node_st *p1,*p2;
	
	p1 = poly_create(a,4);
	if(p1 ==NULL)
		exit(1);
	p2 = poly_create(b,3);
	if(p2 ==NULL)
		exit(1);

	poly_show(p1);
	poly_show(p2);

	poly_union(p1,p2);
	poly_show(p1);



	exit(0);
}
相关推荐
H_BB4 小时前
前缀和算法详解
数据结构·算法
聆风吟º5 小时前
【数据结构手札】时间复杂度详解:概念 | 大O渐进表示法 | 习题
数据结构·算法·时间复杂度·大o渐进表示法
情缘晓梦.5 小时前
C语言分支与循环
c语言·开发语言
AAA.建材批发刘哥6 小时前
03--C++ 类和对象中篇
linux·c语言·开发语言·c++·经验分享
好奇龙猫6 小时前
【大学院-筆記試験練習:线性代数和数据结构(1)】
数据结构·数学
AlexMercer10127 小时前
【操作系统】操作系统期末考试 简答题 焚决
c语言·经验分享·笔记·操作系统
学嵌入式的六子7 小时前
如何使用VScode开发STM32【喂饭级教程】-全过程讲解
c语言·ide·vscode·stm32·单片机·嵌入式硬件
墨辰JC7 小时前
C语言可变参数讲解:stdarg.h应用
c语言·开发语言·蓝桥杯·内存·蓝桥杯嵌入式
C语言小火车7 小时前
C++右值引用与转移语义详解
c语言·开发语言
程芯带你刷C语言简单算法题8 小时前
Day43~实现一个算法求一个数字的树根
c语言·开发语言·算法·c