c++ - C++链表非成员函数反向打印
问题描述
所以我了解了如何使用递归以相反的顺序打印单个链表。我在做非成员函数时遇到了麻烦。例如在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);
}
新增功能
解决方案
标题实际上无法访问列表的内容,除非通过销毁它。所以……这就是我们要做的。
int deleteFromTail(); // delete the tail and return its info;
除了我们需要进行额外的步骤并重建它,因为没有人期望打印容器会破坏其内容。见https://en.wikipedia.org/wiki/Principle_of_least_astonishment
#include <iostream>
#include <stack>
#include <list>
class IntSLList {
public:
int isEmpty() { return m_list.empty(); }
void addToHead(int i) { m_list.push_front(i); }
void addToTail(int i) { m_list.push_back(i); }
int deleteFromHead() {
int temp = m_list.front();
m_list.pop_front();
return temp;
}
int deleteFromTail() {
int temp = m_list.back();
m_list.pop_back();
return temp;
}
private:
// no implementation given so I'm using std::list internally.
std::list<int> m_list;
};
int print_reverse(IntSLList& mylist) {
// store the data we are destroying in temp
IntSLList temp;
// literally the only way we can access the contents of the container is destructive so ... guess we're going there
while (!mylist.isEmpty()) {
int back = mylist.deleteFromTail();
std::cout << back << std::endl;
temp.addToHead(back);
}
// now rebuild the original list. I told you this would be bad.
while (!temp.isEmpty()) {
mylist.addToHead(temp.deleteFromTail());
}
// maybe this was supposed to be length, but not documented so I can return whatever I want.
return -1;
}
int main() {
IntSLList mylist;
mylist.addToTail(1);
mylist.addToTail(2);
mylist.addToTail(3);
print_reverse(mylist);
}
3
2
1
推荐阅读
- linux - 用于 IPC 的命名信号量的 POSIX 实现
- javascript - 为什么我的响应式导航不会切换类?
- python - 您如何获取具有多个相同值的列表,但是当您显示该列表时,您只显示每个唯一值中的一个?
- python - Web抓取python:IndexError:列表索引超出范围
- javascript - 为什么 Safari 中没有出现下拉菜单?
- ios - 快速设置初始视图控制器
- javascript - 如何在数据库中保存密码 - Firebase?
- python - 在 IMDB.com 上为搜索栏中的第一个下拉项查找 Xpath 链接
- python - 将 PowerShell Post 命令转换为 Python Post API 调用
- java - 3个快速for循环整数作业题