两个多项式相加算法(链表实现)

来源:数据结构期中考试补充题

注:该代码测试数据较少,吃过晚饭有时间再测试下改改bug QAQ
//多项式相加:
#include 
using namespace std;

class Node {
     //项的定义
	
public:
	int a;
	int b;
	Node* next;
	Node(int aa, int bb) {
     
		a = aa;
		b = bb;
		next = NULL;;
	}
};
class List{
     
public:
	List() {
     
		Creat();
	}
	Node* head;
	void Creat();
};
void List::Creat() {
     
	int num1, num2;
	cout << "请输入该链表元素个数:" << endl;
	int num;
	cin >> num;
	cout << "请输入组合(空格分隔即可)" << endl;
	head = new Node(1, 1);
	Node* p = head;
	while (num--) {
      //创建一个单链表;
		cin >> num1 >> num2;
		Node* s = new Node(num1, num2);
		p->next = s; 
		p = s;
	}
	p->next = NULL;
}
Node* Add(List &A,List &B) {
     
	Node* pc = A.head;
	Node* pa = A.head->next;
	Node* pb = B.head->next;
	while (pa && pb) {
     
		int num1 = pa->b;
		int num2 = pb->b;
		if (num1 == num2) {
     
			//如果指数相同,加和为0
			if (pa->a + pb->a == 0) {
     
				Node* p1 = pa;
				pa = pa->next;
				Node* p2 = pb;
				pb = pb->next;
				delete p1, p2;
			}
			//指数相同,加和不为0
			else {
     
				pa->a = pa->a + pb->a;
				pc->next = pa;
				pc = pa;
				Node* p = pb;
				pb = pb->next;
				delete(p);
			}
		}
		//如果不相同,将指数小的接入新链表:
		else {
     
			if (num1 < num2) {
     
				pc->next = pa;
				pc = pa;
				pa = pa->next;
			}
			else {
     
				pc->next = pb;
				pc = pb;
				pb = pb->next;
			}
		}
	}
	if (pa == NULL) {
     
		pc->next = pb;
	}
	else pc->next = pa;
	return A.head;
}
//表的定义:
int main() {
     
	cout << "创建链表A:" << endl;
	List A;
	cout << "创建链表B:" << endl;
	List B;
	Node* c=Add(A, B);
	Node* C = c->next;
	while (C != NULL) {
     
		cout << C->a << "*" << "X" << C->b << ' ';
		C = C->next;
	}
	return 0;
}


欢迎各位的讨论交流和批评指正:)

你可能感兴趣的:(数据结构,数据结构,c++,链表,算法)