<分区>
在链表中,我想将每个节点与另一个节点进行比较,如果它们相似,则将它们加在一起。我在遍历链表然后加在一起时遇到问题。
我的 main.cpp:
#include <cstdlib>
#include "list.h"
int main(){
Poly poly=new_list();
Poly poly2=new_list();
Poly merged= new_list();
int n;
int deg;
float coef;
n=1;
while (n==1)
{
cout<<"Enter coefficient ";
cin>> coef;
cout<<"Enter degree ";
cin>>deg;
insert_front(&poly,coef,deg);
cout<<"Enter 1 to continue or 0 to break ";
cin>>n;
}
print_list(poly);
cout<<"sorted\n";
reduce(poly);
}
这是我的头文件:
//list.h
#include <iostream>
using namespace std;
#ifndef LIST_H
#define LIST_H
struct Term {
int deg;
float coef;
Term *next;
};
typedef Term* Poly;
Poly new_list();
void insert_front(Poly* ppoly,int deg, float coef);
void print_list(Poly poly);
void delete_front(Poly* ppoly);
bool is_empty(Poly poly);
Poly merge(Poly *ppoly,Poly *ppoly2);
void split_list(Poly* ppoly,Poly *ppoly2);
void mergesort(Poly* pl);
void reduce(Poly poly);
#endif
我拥有所有函数,可以将用户系数和多项式的次数打印出来,并将它们从最低到最高次数合并排序。
功能:
列表.cpp
#include "list.h"
保利 new_list(){
保利保利= 0;
返回聚;
}
void insert_front(Poly* ppoly,int deg, float coef){
任期*吨;
t = 新任期;
t->系数=系数;
t->度=度;
t->next = *ppoly;
*ppoly = t;
返回;
}
void print_list(聚聚){
项* p;
p = 多边形;
如果(p == 0)
cout << "--- 空列表 ---";
而(p!=0){
cout << p->deg<<"x^"
t = (*ppoly);
*ppoly = (*ppoly)->下一步;
删除吨;
}
bool is_empty(Poly poly){
return (poly == 0); //return true if list empty
}
Poly merge(Poly* ppoly, Poly* ppoly2){
Term **pp;
Poly merged, list1,list2;
merged= new_list();
list1 = *ppoly;
list2 = *ppoly2;
pp= &merged;
while(list1 != NULL && list2 != NULL){
if(list2->coef > list1->coef){
*pp = list1;
list1 = list1->next;
(*pp)->next = NULL;
}else{
*pp = list2;
list2 = list2->next;
(*pp)->next = NULL;
}
pp = &( (*pp)->next );
}
if(list1 != NULL)
*pp = list1;
if(list2 != NULL)
*pp = list2;
*ppoly = NULL;
*ppoly2 = NULL;
return merged;
}
void split_list(Poly* ppoly, Poly* ppoly2){
Poly l1= *ppoly;
Poly l2= *ppoly;
Poly* pp = &l1;
while( l2 != NULL){
l2 = l2->next;
if(l2 != NULL){
l2 = l2->next;
pp = &((*pp)->next);
}
}
l2 = *pp;
(*pp) = NULL;
*ppoly=l1;
*ppoly2=l2;
}
void mergesort(Poly* pl){
Poly l1 = *pl;
Poly l2 = new_list();
Poly merged = new_list();
if(l1 == NULL || l1->next == NULL)
return; //sorted or empty
split_list(&l1,&l2);
mergesort(&l1);
mergesort(&l2);
merged = merge(&l1,&l2);
*pl = merged;
}
void reduce(Poly poly){
mergesort(&poly);
print_list(poly);
int i=0;
cout<<"combining like terms:"<<endl;
Term* p;
p=poly;
if (p==0)
cout<<"---empty list---";
while(i=0){
if (poly->coef==(poly->next)->coef){
p->deg=(poly->deg)+((poly->next)->deg);
poly=p;
i=1;
}
}
print_list(poly);
}
我已经这样做了几天,但无法正常工作。问题出在 reduce()
函数中。
例如,如果我有:2x^2+2x^2+4x^2+3x^5
,它会打印8x^2+3x^5
。