【发布时间】:2021-02-15 15:56:32
【问题描述】:
所以我了解了如何使用递归以相反的顺序打印单个链表。我在做非成员函数时遇到了麻烦。
例如在int print_reverse(IntSLList & list)) 函数中如何以迭代方式打印反向?
************************ .h file **************************
class IntSLLNode {
public:
IntSLLNode() {
next = 0;
}
IntSLLNode(int el, IntSLLNode *ptr = 0) {
info = el; next = ptr;
}
int info;
IntSLLNode *next;
};
class IntSLList {
public:
IntSLList() {
head = 0;
}
~IntSLList();
int isEmpty() {
return head == 0;
}
void addToHead(int);
void addToTail(int);
int deleteFromHead(); // delete the head and return its info;
int deleteFromTail(); // delete the tail and return its info;
bool isInList(int) const;
void printAll() const;
private:
IntSLLNode *head;
};
这里是主要的
************************ main **************************
#include <iostream>
using namespace std;
#include "intSLList.h"
int print_reverse(IntSLList & list){
if (head == NULL)
return;
printReverse(head->next);
cout << head->data << " ";
//How to compelete this in an iterative(or recursive if iterative is too much work)way ?
//like this?
}
int main() {
IntSLList list;
list.print_reverse(list);
}
新增功能
【问题讨论】:
-
向前迭代并将每个元素放入堆栈中。通过弹出直到它为空来打印堆栈的内容。
-
我假设您不允许使用双向链表。如果是这种情况,您必须将元素放入可以从头到尾迭代的容器中。递归解决方案更简单。
-
@drescherjm 是的。我尝试使用递归,但一直遇到错误,这就是我尝试迭代的原因,但如果它过于复杂,那么使用递归方法会很棒
-
也就是说,如果您发布您的递归解决方案,那么我们在这里散落的一条聪明的裤子很可能会告诉您如何解决它。只要尝试是可信的,尝试提出问题几乎总是比将函数留空要好。
-
这不可能。此处发布的标题也没有提供任何向前迭代的方法。或者做任何事。
标签: c++ class linked-list non-member-functions