我们这个世界的一个问题是,蠢人信誓旦旦,智人满腹狐疑。
——Bertrand Russell

文章目录

  • 单链表定义
    • 重载pair的输出运算符
    • 求和函数
  • 总体代码

多项式求和, 即输入两个多项式, 然后将它们合并为一个多项式, 解决多项式求和问题是链表的应用之一。
用链表的原因是, 多项式的指数可能不是连续的, 当指数最大值很高而离散度很高时, 用线性表存储会导致空间利用率很低。 于是可以使用动态开辟结点的链表来进行优化。

首先呈上老师的代码

#include <stdio.h>
#include <malloc.h>/*** Linked list of integers. The key is data. The key is sorted in non-descending order.*/
typedef struct LinkNode{int coefficient;int exponent;struct LinkNode *next;
} *LinkList, *NodePtr;/*** Initialize the list with a header.* @return The pointer to the header.*/
LinkList initLinkList(){LinkList tempHeader = (LinkList)malloc(sizeof(struct LinkNode));tempHeader->coefficient = 0;tempHeader->exponent = 0;tempHeader->next = NULL;return tempHeader;
}// Of initLinkList/*** Print the list.* @param paraHeader The header of the list.*/
void printList(LinkList paraHeader){NodePtr p = paraHeader->next;while (p != NULL) {printf("%d * 10^%d + ", p->coefficient, p->exponent);p = p->next;}// Of whileprintf("\r\n");
}// Of printList/*** Print one node for testing.* @param paraPtr The pointer to the node.* @param paraChar The name of the node.*/
void printNode(NodePtr paraPtr, char paraChar){if (paraPtr == NULL) {printf("NULL\r\n");} else {printf("The element of %c is (%d * 10^%d)\r\n", paraChar, paraPtr->coefficient, paraPtr->exponent);}// Of while
}// Of printNode/*** Add an element to the tail.* @param paraCoefficient The coefficient of the new element.* @param paraExponent The exponent of the new element.*/
void appendElement(LinkList paraHeader, int paraCoefficient, int paraExponent){NodePtr p, q;// Step 1. Construct a new node.q = (NodePtr)malloc(sizeof(struct LinkNode));q->coefficient = paraCoefficient;q->exponent = paraExponent;q->next = NULL;// Step 2. Search to the tail.p = paraHeader;while (p->next != NULL) {p = p->next;}// Of while// Step 3. Now add/link.p->next = q;
}// Of appendElement/*** Polynomial addition.* @param paraList1 The first list.* @param paraList2 The second list.*/
void add(NodePtr paraList1, NodePtr paraList2){NodePtr p, q, r, s;// Step 1. Search to the position.p = paraList1->next;printNode(p, 'p');q = paraList2->next;printNode(q, 'q');r = paraList1; // Previous pointer for inserting.printNode(r, 'r');free(paraList2); // The second list is destroyed. while ((p != NULL) && (q != NULL)) {if (p->exponent < q->exponent) {//Link the current node of the first list.printf("case 1\r\n");r->next = p;r = p;printNode(r, 'r');p = p->next;printNode(p, 'p');} else if ((p->exponent > q->exponent)) {//Link the current node of the second list.printf("case 2\r\n");r->next = q;r = q;printNode(r, 'r');q = q->next;printNode(q, 'q');} else {printf("case 3\r\n");//Change the current node of the first list.p->coefficient = p->coefficient + q->coefficient;printf("The coefficient is: %d.\r\n", p->coefficient);if (p->coefficient == 0) {printf("case 3.1\r\n");s = p;p = p->next;printNode(p, 'p');// free(s);} else {printf("case 3.2\r\n");r = p;printNode(r, 'r');p = p->next;printNode(p, 'p');}// Of ifs = q;q = q->next;//printf("q is pointing to (%d, %d)\r\n", q->coefficient, q->exponent);free(s);}// Of ifprintf("p = %ld, q = %ld \r\n", p, q);} // Of whileprintf("End of while.\r\n");if (p == NULL) {r->next = q;} else {r->next = p;} // Of ifprintf("Addition ends.\r\n");
}// Of add/*** Unit test 1.*/
void additionTest1(){// Step 1. Initialize the first polynomial.LinkList tempList1 = initLinkList();appendElement(tempList1, 7, 0);appendElement(tempList1, 3, 1);appendElement(tempList1, 9, 8);appendElement(tempList1, 5, 17);printList(tempList1);// Step 2. Initialize the second polynomial.LinkList tempList2 = initLinkList();appendElement(tempList2, 8, 1);appendElement(tempList2, 22, 7);appendElement(tempList2, -9, 8);printList(tempList2);// Step 3. Add them to the first.add(tempList1, tempList2);printf("The result is: ");printList(tempList1);printf("\r\n");
}// Of additionTest1/*** Unit test 2.*/
void additionTest2(){// Step 1. Initialize the first polynomial.LinkList tempList1 = initLinkList();appendElement(tempList1, 7, 0);appendElement(tempList1, 3, 1);appendElement(tempList1, 9, 8);appendElement(tempList1, 5, 17);printList(tempList1);// Step 2. Initialize the second polynomial.LinkList tempList2 = initLinkList();appendElement(tempList2, 8, 1);appendElement(tempList2, 22, 7);appendElement(tempList2, -9, 10);printList(tempList2);// Step 3. Add them to the first.add(tempList1, tempList2);printf("The result is: ");printList(tempList1);printf("\r\n");
}// Of additionTest2/*** The entrance.*/
int main(){additionTest1();additionTest2();printf("Finish.\r\n");return 0;
}// Of main

单链表定义

#include <iostream>
#include <vector>
#define remilia int
#define isMyWife mainusing namespace std;template<class ElemType>
class LinkedList {private:class Node {private:ElemType data;Node* next;public:virtual ~Node() {}Node();Node(ElemType data, Node* next) {this -> data = data;this -> next = next;    }ElemType getData() {return this -> data;}void setData(ElemType elem) {this -> data = elem;}Node* getNext() {return this -> next;}void setNext(Node* node) {this -> next = node;}};int length;Node* head;Node* tail;// 引入迭代器 Node* iterator;public:virtual ~LinkedList();LinkedList();LinkedList(vector<ElemType> v);Node* initIterator() {return (this -> iterator = this -> head);}// get the length of linkedlistint getLength();// print all of the linkedlistvoid outputList();/*** @brief  append a node to the tail* @return the result of appending  1 -> success* @param elem * the appending is always successful**/bool pushBack(ElemType elem);/*** @brief append a node to the head* @param elem * @return the result of appending  1 -> success* the appending is always successful**/bool pushHead(ElemType elem);/*** @brief delete a node from head* @return the result of deleting 1 -> success, 0 -> failute* the reason of failure is that the head node isn't existed**/bool popHead();/*** @brief delete a node from tail* @return the result of deleting 1 -> success, 0 -> failute* the reason of failure is that the tail node isn't existed* @return **/bool popBack();// insert an element to the given positionbool insertElement(int paraPosition, ElemType elem);/*** @brief delete a node by the paraPosition* @param the position of the node needed deleted* @return 1 -> success, 0 -> fail* the reason of failure is the position out of range**/bool deleteElementByParaPosition(int paraPosition); /*** @brief clear the list* **/void clear();/*** @brief get a element by paraPosition* * * @return the element**/ElemType getElement(int paraPosition);
}; template<class ElemType>
LinkedList<ElemType>::~LinkedList() {}template<class ElemType>
LinkedList<ElemType>::LinkedList() {this -> length = 0;this -> head = this -> tail = nullptr;
}template<class ElemType>
LinkedList<ElemType>::LinkedList(vector<ElemType> v) {for (auto e : v) {this -> pushBack(e);}
}template<class ElemType>
bool LinkedList<ElemType>::pushBack(ElemType elem) {// if the tail equals null, the head equals null tooif (this -> tail == nullptr) {this -> head = this -> tail = new Node(elem, nullptr);} else {Node* newTail = new Node(elem, nullptr);this -> tail -> setNext(newTail);this -> tail = newTail; }this -> length++;return 1;
}template<class ElemType>
bool LinkedList<ElemType>::pushHead(ElemType elem) {if (this -> head == nullptr) {this -> head = this -> tail = new Node(elem, nullptr);} else {Node* newTail = new Node(elem, head);this -> head = newTail;}this -> length++;return 1;
}template<class ElemType>
bool LinkedList<ElemType>::popHead() {if (this -> length == 1) {this -> head = this -> tail = nullptr;}if (this -> head == nullptr) {return 0;} else {Node* temp = this -> head;this -> head = this -> head -> getNext();delete temp;return 1;}
}template<class ElemType>
bool LinkedList<ElemType>::popBack() {if (this -> length == 1) {this -> head = this -> tail = nullptr;}if (this -> tail == nullptr) {return 0;} else {Node* temp = this -> head;while (temp -> getNext() != this -> tail) {temp = temp -> getNext();}delete temp -> getNext();this -> tail = temp;return 1;}
}template<class ElemType>
void LinkedList<ElemType>::outputList() {Node* temp = this -> head;while (temp != nullptr) {cout << temp -> getData() << " ";temp = temp -> getNext();} putchar('\n');
}template<class ElemType>
int LinkedList<ElemType>::getLength() {return this -> length;
}template<class ElemType>
void LinkedList<ElemType>::clear() {Node* temp = this -> head;Node* storge = temp;while (temp != nullptr) {temp = temp -> getNext();delete storge;storge = temp;}  delete storge;this -> head = this -> tail = nullptr;this -> length = 0;
}template<class ElemType>
bool LinkedList<ElemType>::deleteElementByParaPosition(int paraPosition) {if (paraPosition > this -> getLength()) {return 0;}if (paraPosition == 1) {return popHead();}int recordIndex = 1;Node* temp = this -> head;while (recordIndex < paraPosition - 1) {temp = temp -> getNext();    recordIndex++;}Node* recorder = temp -> getNext();temp -> setNext(recorder -> getNext());delete recorder;return 1;
}template<class ElemType>
bool LinkedList<ElemType>::insertElement(int paraPosition, ElemType elem) {if (paraPosition > this -> getLength() + 1) {return 0;  }if (paraPosition == 1) {return this -> pushHead(elem);}Node* temp = this -> head;int recordIndex = 1;while (recordIndex < paraPosition - 1) {temp = temp -> getNext();recordIndex++;    }Node* newNode = new Node(elem, temp -> getNext());temp -> setNext(newNode);this -> length++;return 1;
}template<class ElemType>
ElemType LinkedList<ElemType>::getElement(int paraPosition) {if (paraPosition > this -> length) {throw "out of range...";}int recordIndex = 1;Node* temp = this -> head;while (recordIndex < paraPosition) {temp = temp -> getNext();recordIndex++;}return temp -> getData();
}remilia isMyWife() {return 0;
}

重载pair的输出运算符

// 重载pair的输出运算符
template<class T, class U>
std::ostream& operator<<(std::ostream& os, const std::pair<T, U>& p) {os << p.first << "x^" << p.second << " ";return os;
}

求和函数

// 参数使用pair
// pair<系数, 指数>
LinkedList<pair<int, int>> add(LinkedList<pair<int, int>>& a, LinkedList<pair<int, int>>& b) {// Node是内部私有类, 因此这里使用自动类型进行推断 LinkedList<pair<int, int>> ans;auto iteratorA = a.initIterator();auto iteratorB = b.initIterator();while (iteratorA && iteratorB) {if (iteratorA -> getData().second < iteratorB -> getData().second) {ans.pushBack({iteratorA -> getData().first, iteratorA -> getData().second});iteratorA = iteratorA -> getNext();} else if (iteratorA -> getData().second > iteratorB -> getData().second) {ans.pushBack({iteratorB -> getData().first, iteratorB -> getData().second});iteratorB = iteratorB -> getNext();} else {int sum = iteratorA -> getData().second + iteratorB -> getData().second;if (sum) {ans.pushBack({sum, iteratorA -> getData().second});}iteratorA = iteratorA -> getNext();iteratorB = iteratorB -> getNext();}}while (iteratorA) {ans.pushBack({iteratorA -> getData().first, iteratorA -> getData().second});iteratorA = iteratorA -> getNext();}while (iteratorB) {ans.pushBack({iteratorB -> getData().first, iteratorB -> getData().second});iteratorB = iteratorB -> getNext();}a.clear();b.clear();return ans;
}

总体代码

#include <bits/stdc++.h>
#define remilia int
#define isMyWife mainusing namespace std;// 重载pair的输出运算符
template<class T, class U>
std::ostream& operator<<(std::ostream& os, const std::pair<T, U>& p) {os << p.first << "x^" << p.second << " ";return os;
}template<class ElemType>
class LinkedList {private:class Node {private:ElemType data;Node* next;public:virtual ~Node() {}Node();Node(ElemType data, Node* next) {this -> data = data;this -> next = next;    }ElemType getData() {return this -> data;}void setData(ElemType elem) {this -> data = elem;}Node* getNext() {return this -> next;}void setNext(Node* node) {this -> next = node;}};   int length;Node* head;Node* tail;public:virtual ~LinkedList();LinkedList();LinkedList(vector<ElemType> v);// 引入迭代器 Node* iterator;Node* initIterator() {return (this -> iterator = this -> head);}// get the length of linkedlistint getLength();// print all of the linkedlistvoid outputList();/*** @brief  append a node to the tail* @return the result of appending  1 -> success* @param elem * the appending is always successful**/bool pushBack(ElemType elem);/*** @brief append a node to the head* @param elem * @return the result of appending  1 -> success* the appending is always successful**/bool pushHead(ElemType elem);/*** @brief delete a node from head* @return the result of deleting 1 -> success, 0 -> failute* the reason of failure is that the head node isn't existed**/bool popHead();/*** @brief delete a node from tail* @return the result of deleting 1 -> success, 0 -> failute* the reason of failure is that the tail node isn't existed* @return **/bool popBack();// insert an element to the given positionbool insertElement(int paraPosition, ElemType elem);/*** @brief delete a node by the paraPosition* @param the position of the node needed deleted* @return 1 -> success, 0 -> fail* the reason of failure is the position out of range**/bool deleteElementByParaPosition(int paraPosition); /*** @brief clear the list* **/void clear();/*** @brief get a element by paraPosition* * * @return the element**/ElemType getElement(int paraPosition);
}; template<class ElemType>
LinkedList<ElemType>::~LinkedList() {}template<class ElemType>
LinkedList<ElemType>::LinkedList() {this -> length = 0;this -> head = this -> tail = nullptr;
}template<class ElemType>
LinkedList<ElemType>::LinkedList(vector<ElemType> v) {for (auto e : v) {this -> pushBack(e);}
}template<class ElemType>
bool LinkedList<ElemType>::pushBack(ElemType elem) {// if the tail equals null, the head equals null tooif (this -> tail == nullptr) {this -> head = this -> tail = new Node(elem, nullptr);} else {Node* newTail = new Node(elem, nullptr);this -> tail -> setNext(newTail);this -> tail = newTail; }this -> length++;return 1;
}template<class ElemType>
bool LinkedList<ElemType>::pushHead(ElemType elem) {if (this -> head == nullptr) {this -> head = this -> tail = new Node(elem, nullptr);} else {Node* newTail = new Node(elem, head);this -> head = newTail;}this -> length++;return 1;
}template<class ElemType>
bool LinkedList<ElemType>::popHead() {if (this -> length == 1) {this -> head = this -> tail = nullptr;}if (this -> head == nullptr) {return 0;} else {Node* temp = this -> head;this -> head = this -> head -> getNext();delete temp;return 1;}
}template<class ElemType>
bool LinkedList<ElemType>::popBack() {if (this -> length == 1) {this -> head = this -> tail = nullptr;}if (this -> tail == nullptr) {return 0;} else {Node* temp = this -> head;while (temp -> getNext() != this -> tail) {temp = temp -> getNext();}delete temp -> getNext();this -> tail = temp;return 1;}
}template<class ElemType>
void LinkedList<ElemType>::outputList() {Node* temp = this -> head;while (temp != nullptr) {cout << temp -> getData() << " ";temp = temp -> getNext();} putchar('\n');
}template<class ElemType>
int LinkedList<ElemType>::getLength() {return this -> length;
}template<class ElemType>
void LinkedList<ElemType>::clear() {Node* temp = this -> head;Node* storge = temp;while (temp != nullptr) {temp = temp -> getNext();delete storge;storge = temp;}  delete storge;this -> head = this -> tail = nullptr;this -> length = 0;
}template<class ElemType>
bool LinkedList<ElemType>::deleteElementByParaPosition(int paraPosition) {if (paraPosition > this -> getLength()) {return 0;}if (paraPosition == 1) {return popHead();}int recordIndex = 1;Node* temp = this -> head;while (recordIndex < paraPosition - 1) {temp = temp -> getNext();    recordIndex++;}Node* recorder = temp -> getNext();temp -> setNext(recorder -> getNext());delete recorder;return 1;
}template<class ElemType>
bool LinkedList<ElemType>::insertElement(int paraPosition, ElemType elem) {if (paraPosition > this -> getLength() + 1) {return 0;  }if (paraPosition == 1) {return this -> pushHead(elem);}Node* temp = this -> head;int recordIndex = 1;while (recordIndex < paraPosition - 1) {temp = temp -> getNext();recordIndex++;    }Node* newNode = new Node(elem, temp -> getNext());temp -> setNext(newNode);this -> length++;return 1;
}template<class ElemType>
ElemType LinkedList<ElemType>::getElement(int paraPosition) {if (paraPosition > this -> length) {throw "out of range...";}int recordIndex = 1;Node* temp = this -> head;while (recordIndex < paraPosition) {temp = temp -> getNext();recordIndex++;}return temp -> getData();
}// 参数使用pair
// pair<系数, 指数>
LinkedList<pair<int, int>> add(LinkedList<pair<int, int>>& a, LinkedList<pair<int, int>>& b) {// Node是内部私有类, 因此这里使用自动类型进行推断 LinkedList<pair<int, int>> ans;auto iteratorA = a.initIterator();auto iteratorB = b.initIterator();while (iteratorA && iteratorB) {if (iteratorA -> getData().second < iteratorB -> getData().second) {ans.pushBack({iteratorA -> getData().first, iteratorA -> getData().second});iteratorA = iteratorA -> getNext();} else if (iteratorA -> getData().second > iteratorB -> getData().second) {ans.pushBack({iteratorB -> getData().first, iteratorB -> getData().second});iteratorB = iteratorB -> getNext();} else {int sum = iteratorA -> getData().second + iteratorB -> getData().second;if (sum) {ans.pushBack({sum, iteratorA -> getData().second});}iteratorA = iteratorA -> getNext();iteratorB = iteratorB -> getNext();}}while (iteratorA) {ans.pushBack({iteratorA -> getData().first, iteratorA -> getData().second});iteratorA = iteratorA -> getNext();}while (iteratorB) {ans.pushBack({iteratorB -> getData().first, iteratorB -> getData().second});iteratorB = iteratorB -> getNext();}a.clear();b.clear();return ans;
}remilia isMyWife() {srand(time(NULL));LinkedList<pair<int, int>> a, b, c;for (int i = 1; i <= 10; i++) {a.pushBack({i, i});}for (int j = 10; j <= 20; j++) {b.pushBack({j, j});}c = add(a, b);c.outputList();return 0;
}

线性表应用 多项式加法相关推荐

  1. 实习一 线性表及其应用 (题目:一元稀疏多项式的加法运算 )

    一.需求分析 1.输入并建立两个多项式: 2.多项式a与b相加,建立和多项式c: 3.输出多项式a,b,c.输出格式:比如多项式a为:A(x)=c1xe1+ c2xe2+-+ cmxem,其中,ci和 ...

  2. c语言加法减法乘法,一元多项式的加法减法乘法c语言描述线性表应用

    一元多项式的加法减法乘法 --(c语言描述)线性表应用 来源:永远的北邮人 vc6.0下调试通过 #include #include #include #include #include #inclu ...

  3. 线性表的应用——多项式的计算

    应用顺序表计算多项式,把多项式存储在顺序表里,顺序表的下标对应多项式的系数 #include <stdio.h> #include <stdlib.h> #define MAX ...

  4. E. DS线性表—多项式相加

    [id:24][20分]E. DS线性表-多项式相加 题目描述 对于一元多项式 p(x)=p0+p1x+p2x2+ - +pnxn ,每个项都有系数和指数两部分,例如p2x2的系数为p2,指数为2. ...

  5. 第二次作业--线性表

    一.题目 1.6-3 jmu-ds-链表倒数第m个数 1.题目要求 2.设计思路 int Find(){ 设置i.j; while(){ i随着遍历链表增加,使得i的值为链表长度;} for(){ 运 ...

  6. 数据结构与算法基础02:线性表

    目录 1. 线性表抽象数据类型 1.1 概述 1.2 抽象数据类型 2. 线性表的顺序表示和实现 2.1 概述 2.1.1 存储方式 2.1.2 逻辑关系表示 2.1.3 操作特性 2.2 实现 2. ...

  7. C语言实现两个多项式加法与乘法

    加法实现: 先说一下,我用了两种方法实现,一种是顺序表实现,一种是链表实现,所以,为了方便,将两种方法分别写成头文件了,主函数是一样的 方法一(顺序表实现) 直接上代码,头文件"List.h ...

  8. 数据结构线性表的逻辑结构(三)顺序表基本操作的实现

    一. 实验目的 1. 掌握线性表的逻辑结构: 2. 顺序表基本操作的实现: 3. 掌握利用C/C++编程语言实现数据结构的编程方法: 4. 通过上机时间加强利用数据结构解决实际应用问题的能力: 二.  ...

  9. 线性表实现多项式相加c语言,用线性表实现多个多项式相加

    今天开始想复习一下数据结构,就从线性表开始吧. 今天是用线性表实现多个多项式相加这个题目,自变量是x. 题目描述如下: 在数学上,一个一元多项式Pn(x)可按降幂写成:Pn(x) = pn x^n + ...

最新文章

  1. C++ 对引用的理解2
  2. SpringBoot2 集成 xxl-job任务调度中心_参数传递
  3. linux jlink软件安装,LINUX下安装JLINK
  4. idea jdbc封装_真赞!IDEA 中这么玩 MyBatis,让编码速度飞起!
  5. CMD终端关于pip报错,scrapy报错的一种处理方法
  6. java random()_JAVA的Random类的用法详解
  7. python通过win32com库播放mp3文件的代码
  8. 为什么没有黑客攻击棋牌游戏
  9. 解决AppUpdate不能使用的问题
  10. 阿里亮相 SIGCOMM2017 调度系统NetO惊艳全场
  11. 2022危险化学品经营单位主要负责人特种作业证考试题库及答案
  12. 数据库数据迁移失败,如何进行修复操作
  13. linux中继器设置密码,无线扩展器管理员密码_初始密码是多少?-192路由网
  14. 腾讯月薪1.5W扩招毕业生,看到要求我傻眼了!
  15. matlab vvvs电机,MATLAB/Simulink在控制系统仿真与CAD应用(一)
  16. Symbian开发入门
  17. STM3利用FATFS向SD卡文件追加数据的三种方法
  18. 故障001:安全版-资源限制
  19. 家用计算机怎么更新,Win7家庭版如何升级为旗舰版
  20. 【干货】通俗易懂的IT审计资料,提供高清PDF下载

热门文章

  1. 写出求abc中最大数的c语言表达式,有3个整数abc由键盘输入输出其中最大的数
  2. 从一笔金币充值去思考分布式事务
  3. CSS实现文字垂直居中
  4. 【笔记】 Hard negative:区域建议框中得分较高的False Positive(假阳性)
  5. 電子郵件退信原因及寄信錯誤查詢
  6. CHECK的简单用法
  7. gitee仓库创建和git一些常见命令
  8. 狗屎一样的面试官,你遇到过几个?
  9. Windows10系统重启后使用TEMP(临时)账户略解
  10. (4.2.49)微信APM:Matrix源码浅析