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);
}
相关推荐
学习编程的gas25 分钟前
数据结构——八大排序算法
数据结构·算法·排序算法
暖阳华笺39 分钟前
Leetcode刷题 由浅入深之哈希表——242. 有效的字母异位词
数据结构·c++·算法·leetcode·哈希表
Smark.1 小时前
数据结构之BFS广度优先算法(腐烂的苹果)
数据结构·算法·宽度优先
代码程序猿RIP1 小时前
C++(22)—内存管理
开发语言·数据结构·c++·算法
奇树谦2 小时前
C/C++语言常见问题-智能指针、多态原理
c语言·开发语言·c++
庐阳寒月2 小时前
linux多线(进)程编程——(8)多进程的冲突问题
linux·c语言·嵌入式
八股文领域大手子3 小时前
深入浅出 Redis:核心数据结构解析与应用场景Redis 数据结构
java·数据结构·数据库·人工智能·spring boot·redis·后端
一只专注api接口开发的技术猿3 小时前
基于 Java 的淘宝 API 调用实践:商品详情页 JSON 数据结构解析与重构
大数据·数据结构·重构·json
可乐^奶茶4 小时前
2026《数据结构》考研复习笔记二(C++面向对象)
数据结构·c++·笔记
槐月杰7 小时前
C语言中冒泡排序和快速排序的区别
c语言·算法·排序算法