数据结构问题
写算法,借助于栈将一个单链表逆置 #include <iostream>#include <stack>
#include <list>
using std::stack, std::list;
using std::cout, std::endl;
using std::ostream;
template<typename T>
list<T> reverse(const list<T> &l) {
stack<T> s;
for(const auto &i: l) s.push(i);
list<T> result;
while(!s.empty()) {
result.push_back(s.top());
s.pop();
}
return result;
}
template<typename T>
ostream &operator<<(ostream &os, const list<T> &rhs) {
for(const auto &i: rhs) os << i << " ";
return os;
}
int main() {
{
list<int> la = {1, 2, 3, 4};
list<int> lb = reverse(la);
cout << lb << endl;
}
{
list<double> la = {11.23, 2.56, 3.98, 4.73};
list<double> lb = reverse(la);
cout << lb << endl;
}
return 0;
}
去看看力控大佬清晰的解题思路:
剑指 Offer II 024. 反转链表
s.top
页:
[1]