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);
}
相关推荐
小猫咪怎么会有坏心思呢24 分钟前
华为OD机考 - 水仙花数 Ⅰ(2025B卷 100分)
数据结构·链表·华为od
乖乖是干饭王36 分钟前
Linux系统编程中的_GNU_SOURCE宏
linux·运维·c语言·学习·gnu
weixin_4786897640 分钟前
C++ 对 C 的兼容性
java·c语言·c++
hn小菜鸡1 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
待什么青丝2 小时前
【TMS570LC4357】之相关驱动开发学习记录2
c语言·arm开发·驱动开发·单片机·学习
小柯博客2 小时前
从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(九)
c语言·stm32·单片机·嵌入式硬件·物联网
CodeWithMe3 小时前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
全栈凯哥4 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥4 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu4 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode