C语言单链表实现多项式相加

2025-05-27 0 63

本文实例为大家分享了C语言单链表实现多项式相加的具体代码,供大家参考,具体内容如下

?

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
//多项式的相加和相乘

#include<stdio.h>

#include<stdlib.h>

#pragma warning(disable:4996)//兼容scanf

typedef struct node {

int coef;

int expon;

struct node* link;

}Polynode,*Polynomial;

Polynomial InsertPolyLinklist(Polynomial in,Polynomial Pread) {

Pread->link = in;

Pread = in;

in->link = NULL;

return Pread;

}

Polynomial ReadPoly(void) {

Polynomial Pread = (Polynomial)malloc(sizeof(Polynode));

Pread->link = NULL;

Polynomial H = Pread;

int N;

scanf("%d ", &N);

while (N--) {

Polynomial p = (Polynomial)malloc(sizeof(Polynode));

scanf("%d %d", &p->coef, &p->expon);

Pread= InsertPolyLinklist(p,Pread);

}

Polynomial F;

F = H->link;

free(H);

return F;

}

void PrintPoly(Polynomial F) {

while(F != NULL) {

printf("%d %d ", F->coef, F->expon);

F = F->link;

}

printf("\\n");

}

Polynomial Add(Polynomial p1, Polynomial p2) {

Polynomial t1=p1,t2=p2;

Polynomial p=(Polynomial)malloc(sizeof(Polynode));

p->link = NULL;

Polynomial q = p;

Polynomial read;

while (t1&&t2) {

if (t1->expon == t2->expon) {

if (t1->coef + t2->coef) {

t1->coef = t1->coef + t2->coef;

t1->expon = t1->expon;

read = t1;

q->link = read;

q = read;

t1 = t1->link;

t2 = t2->link;

}

}

else {

if (t1->expon > t2->expon){

read = t1;

q->link = read;

q = read;

t1 = t1->link;

}

else {

if (t1->expon < t2->expon) {

read = t2;

q->link = read;

q = read;

t2 = t2->link;

}

}

}

}

if (t1) {

q->link = t1;

}

if (t2) {

q->link = t2;

}

Polynomial F = p->link;

free(p);

return F;

}

int main(void) {

Polynomial p1, p2, pp, ps;

p1 = ReadPoly();

PrintPoly(p1);

p2 = ReadPoly();

PrintPoly(p2);

pp = Add(p1, p2);

PrintPoly(pp);

// ps = Mult(p1, p2);

// PrintPoly(ps);

return 0;

}

参考

MOOC 浙大数据结构

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C语言单链表实现多项式相加 https://www.kuaiidc.com/73182.html

相关文章

猜你喜欢
发表评论
暂无评论