点:抽象问题简化问题
题意:单链表,从尾到头打印
如原始链表:0 1 2 3 4 5 6 7 8 9
则应该打印:9 8 7 6 5 4 3 2 1 0
思路:如果做链表逆序,会破坏原始链表。这是应该倒过来想。
递归、栈,是倒过来想的常用伎俩,是解决很多面试题的思路。
本题的方案就是:顺序遍历一次,把每个节点值依次入栈,可以显示用栈也可以递归,最好是显示入栈,然后再挨个出栈打印就行。
代码:
#include <iostream>
#include <stack>
template<class T> struct Node {
T val;
Node *next;
Node(T _val):val(_val), next(nullptr) {}
};
template<class T> class Slist {
Node<T> *root;
public:
Slist():root(nullptr) {}
~Slist () {
Node<T> *cur = root;
while (cur) {
Node<T> *next = cur->next;
delete cur;
cur = next;
}
}
void Add (T val) {
if (!root) {
root = new Node<T>(val);
} else {
Node<T> *cur = root;
while (cur) {
if (cur->next) {
cur = cur->next;
} else {
cur->next = new Node<T>(val);
break;
}
}
}
}
void Show () {
Node<T> *cur = root;
while (cur) {
std::cout << cur->val << "\t";
cur = cur->next;
}
std::cout << std::endl;
}
void Reverse_Show () {
std::stack<T> stk;
Node<T> *cur = root;
while (cur) {
stk.push(cur->val);
cur = cur->next;
}
while (!stk.empty()) {
T v = stk.top();
stk.pop();
std::cout << v << "\t";
}
std::cout << std::endl;
}
};
int main () {
Slist<int> sl;
for (int i = 0; i < 10; i++) {
sl.Add(i);
}
sl.Show();
sl.Reverse_Show();
return 0;
}