下午好,我希望有人能帮助我看看我漏掉了什么。我承认这是一个家庭作业,但我们被允许在代码上进行协作,所以希望这里的某个人不介意提供帮助。
对于这个程序,我需要使用递归和迭代来旋转一组三个项目。我已经成功地完成了递归情况,但迭代版本给我带来了很多麻烦。我尝试过的所有方法都会导致段错误或无限打印。以下是代码,再次感谢任何帮助:
对于这个程序,我需要使用递归和迭代来旋转一组三个项目。我已经成功地完成了递归情况,但迭代版本给我带来了很多麻烦。我尝试过的所有方法都会导致段错误或无限打印。以下是代码,再次感谢任何帮助:
template<typename A, typename B, typename C>
class Triple{
public:
A first;
B second;
C third;
Triple(A a, B b, C c){ first = a; second = b; third = c;}
A fst(){return first;}
B snd(){return second;}
C thd(){return third;}
// The function change1(), changes the first component of a triple.
void change1(A a){ first = a;}
};
// A linked list of triples where the order of the triple rotates as it goes.
template<typename A, typename B, typename C>
class RotateList{
public:
Triple<A,B,C> *t;
RotateList<B,C,A> * next; // Notice the order has changed
RotateList(Triple<A,B,C> *t1, RotateList<B,C,A> * n1){ this->t = t1; this->next = n1;}
/*
* Implement with recursion, creating i triples, each with the order rotated from the
* previous.
*/
static RotateList<A,B,C> * create(A a, B b, C c, int i){
if (i <= 0) return nullptr;
Triple<A,B,C> * t = new Triple<A,B,C>(a,b,c);
RotateList<B,C,A> * n = RotateList<B,C,A>::create(b,c,a, i-1);
return new RotateList<A,B,C>(t, n);
}
/*
* Implement with iteration, using the same instance of the same three triples
* over and over.
*/
static RotateList<A,B,C> * create2(A a, B b, C c, int i){
}
/* Print the whole rotating list. */
void print(){
cout << "{" << t->fst() << " "<< t->snd() << " "<< t->thd() << "}";
if (next != nullptr)
next->print();
else
cout << endl;
}
};
int main(){
float f = 3.14;
int i = 3;
char c = 'c';
Triple<float,int,char> t = Triple<float,int,char>(f,i,c);
Triple<float,int,char> t1 = t;
cout << "Starting triple: [" << t.fst() << " "<< t.snd() << " "<< t.thd() << "]" << endl;
cout << endl << "Rotating list created recursively" << endl;
RotateList<float,int,char> * r= RotateList<float,int,char>::create(f,i,c, 10);
r->print();
r->t->change1(42.42);
r->print();
cout << endl << "Rotating list created iteratively" << endl;
RotateList<float,int,char> * s= RotateList<float,int,char>::create2(f,i,c, 10);
s->print();
s->t->change1(42.42);
s->print();
s->next->t->change1(501);
s->print();
}
我的尝试如下:
static RotateList<A,B,C> * create2(A a, B b, C c, int i) {
RotateList<C,A,B> *l1 = new RotateList<A,B,C>(new Triple<A,B,C>, nullptr);
RotateList<B,C,A> *l2;
RotateList<C,A,B> *l3;
RotateList<A,B,C> *tmp1 = l1;
RotateList<B,C,A> *tmp2;
RotateList<C,A,B> *tmp3;
int nextTriple = 2;
for (i; i > 0; i--) {
tmp3->next = l1;
tmp1 = tmp3->next;
nextTriple = 2;
} else if {
temp1->mext = l2;
tmp2 = tmp1->next;
nextTriple = 3;
} else {
tmp2->next = l3;
tmp3 = tmp2->next;
nextTriple = 1;
}
}
return l1;
}
(2 3 1)
幂的列表,或者老师是如何表述的),即使对于那些认为(写得好的)代码自文档化的人也是如此。 - outis