鱼C论坛

 找回密码
 立即注册
查看: 1392|回复: 3

[已解决]数据结构问题

[复制链接]
发表于 2022-5-9 19:30:21 | 显示全部楼层 |阅读模式
20鱼币
写算法,借助于栈将一个单链表逆置
最佳答案
2022-5-9 19:30:22
  1. #include <iostream>
  2. #include <stack>
  3. #include <list>

  4. using std::stack, std::list;
  5. using std::cout, std::endl;
  6. using std::ostream;

  7. template<typename T>
  8. list<T> reverse(const list<T> &l) {
  9.     stack<T> s;
  10.     for(const auto &i: l) s.push(i);
  11.     list<T> result;
  12.     while(!s.empty()) {
  13.         result.push_back(s.top());
  14.         s.pop();
  15.     }
  16.     return result;
  17. }

  18. template<typename T>
  19. ostream &operator<<(ostream &os, const list<T> &rhs) {
  20.     for(const auto &i: rhs) os << i << " ";
  21.     return os;
  22. }

  23. int main() {
  24.     {
  25.         list<int> la = {1, 2, 3, 4};
  26.         list<int> lb = reverse(la);
  27.         cout << lb << endl;
  28.     }
  29.     {
  30.         list<double> la = {11.23, 2.56, 3.98, 4.73};
  31.         list<double> lb = reverse(la);
  32.         cout << lb << endl;
  33.     }
  34.     return 0;
  35. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-9 19:30:22 | 显示全部楼层    本楼为最佳答案   
  1. #include <iostream>
  2. #include <stack>
  3. #include <list>

  4. using std::stack, std::list;
  5. using std::cout, std::endl;
  6. using std::ostream;

  7. template<typename T>
  8. list<T> reverse(const list<T> &l) {
  9.     stack<T> s;
  10.     for(const auto &i: l) s.push(i);
  11.     list<T> result;
  12.     while(!s.empty()) {
  13.         result.push_back(s.top());
  14.         s.pop();
  15.     }
  16.     return result;
  17. }

  18. template<typename T>
  19. ostream &operator<<(ostream &os, const list<T> &rhs) {
  20.     for(const auto &i: rhs) os << i << " ";
  21.     return os;
  22. }

  23. int main() {
  24.     {
  25.         list<int> la = {1, 2, 3, 4};
  26.         list<int> lb = reverse(la);
  27.         cout << lb << endl;
  28.     }
  29.     {
  30.         list<double> la = {11.23, 2.56, 3.98, 4.73};
  31.         list<double> lb = reverse(la);
  32.         cout << lb << endl;
  33.     }
  34.     return 0;
  35. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-9 20:14:17 | 显示全部楼层

去看看力控大佬清晰的解题思路:

剑指 Offer II 024. 反转链表
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-14 19:30:45 | 显示全部楼层
s.top
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 11:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表