当前位置:   article > 正文

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

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

多项式合并
poly.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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/620636
推荐阅读
相关标签
  

闽ICP备14008679号