1. 程式人生 > >資料結構__兩個多項式乘法運算

資料結構__兩個多項式乘法運算

這個,也是第一次資料結構課程設計的題目

一共四個檔案,分別命名為main.cpp     head.h   list.h    cal.h。作用分別是main函式主程式,基本標頭檔案捲入,單鏈表和其基本操作的定義,計算併合並同類專案操作

註釋就不寫了,因為沒啥好寫的,我也不知道該寫些什麼。

main.cpp

#include"cal.h"
int main(void)
{
	cal();
	system("pause");
	return 0;
}

head.h

#pragma once
#include<iostream>
using namespace std;

list.h

#pragma once
#include"head.h"

typedef struct node
{
	node * next;
	int data;
	int n;
}node;

class lnode {
	node* head;
public:
	lnode() { head = new node; }//1
	~lnode() {}
	void create();
	void specialCreate(int *g,int *h,int m);
	void Print();
	void del();
	int getData();
	int getN();
	void F();
	bool isEmpty() { if (head->next == NULL)return true; else return false; }
};

void lnode::F()
{
	cout << "合併同類項:" << endl;
	node *hashTable[100] = { NULL };//該雜湊用於記錄地址,下標是次方數,NULL則表示以下標為次方數的項不存在
	node *q;
	node *p = head->next;
	while (p)
	{
		if (hashTable[p->n] == NULL)
		{
			hashTable[p->n] = p;
			q = p;
			p = p->next;
		}
		else
		{
			hashTable[p->n]->data = hashTable[p->n]->data + p->data;
			q->next = p->next;
			delete(p);
			p = q->next;
		}
	}
}

void lnode::create()
{
	node *p, *s;
	s = head;
	head->next = NULL;
	int m;
	cout<<"輸入項數:"<<endl;
	cin >> m;
	cout << "依次輸入每個項的係數和次數:" << endl;
	for (int i = 0; i < m; i++)
	{
		p = new node;
		cin >> p->data >> p->n;
		p->next = s->next;
		s->next = p;
	}
	cout << endl;
}

void lnode::specialCreate(int *g, int *h,int m)
{
	node *p, *s;
	s = head;
	head->next = NULL;
	for (int i = 0; i < m; i++)
	{
		p = new node;
		p->data = *g;
		p->n = *h;
		h++;
		g++;
		p->next = s->next;
		s->next = p;
	}
}

int lnode::getData()
{
	node *p = head->next;
	return p->data;
}

int lnode::getN()
{
	node *p = head->next;
	return p->n;
}
void lnode::Print()
{
	cout << "多項式顯示:" << endl;
	node *p = head->next;
	while(p)
	{
		cout << '(' << p->data << ')' << "x^" << p->n;
		p = p->next;
		if (p)cout << '+';
	}
	cout << endl;
}

void lnode::del()
{
	node* q = head;
	node* p = q->next;
	q->next = p->next;
	delete(p);
	p = q->next;
}

cal.h

#pragma once
#include"list.h"

void cal()
{
	lnode A;
	cout << "第一個多項式" << endl;
	A.create();
	A.Print();
	cout << endl;
	lnode B;
	cout << "第二個多項式" << endl;
	B.create();
	B.Print();
	cout << endl;
	int a[100],b[100],c[100],d[100];
	int n = 0,m=0;
	while (!A.isEmpty())
	{
		a[n] = A.getData();
		b[n] = A.getN();
		A.del();
		n++;
	}
	while (!B.isEmpty())
	{
		c[m] = B.getData();
		d[m] = B.getN();
		B.del();
		m++;
	}
	int e[100],f[100];
	int x = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			e[x] = a[i] * c[j];
			f[x] = b[i] + d[j];
			x++;
		}
	}
	cout << "兩個多項式相乘。。。。" << endl;
	lnode C;
	C.specialCreate(e, f, x);
	C.Print();
	C.F();
	C.Print();
}

 

本人學號170310441

最後,輸出圖: