数据结构

xiaoxiao2025-04-14  14

这个,也是第一次数据结构课程设计的题目

一共四个文件,分别命名为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

最后,输出图:

转载请注明原文地址: https://www.6miu.com/read-5028211.html

最新回复(0)