关于反转链表的问题
来源:互联网 发布:看澳洲股市软件 编辑:程序博客网 时间:2024/05/22 14:59
题目:输入一个链表,从尾到头打印链表每个节点的值。
思路:1、最先想到栈的结构,符合先进后出的特点;
2、递归与栈的关系,联想到使用递归的方法来实现(递归结构好好理解一下,感觉自己以前其实没有理解很清楚)
3、用vector从头端插入的思想来解决
代码如下:
思路1的代码,利用栈的结构
int ReverseList(ListNode *head){stack<int> stack;ListNode *p;p = head->next;while (p != NULL){stack.push(p->val);p = p->next;}while (!stack.empty()){cout<<stack.top();stack.pop();}return 0;}
思路2的代码:
#include<iostream>#include<iomanip>#include <iostream>#include <stdio.h>#include <string.h>#include <list>#include<vector>#include <cstdio>#include <iostream>#include <stack>#include <queue>using namespace std;struct ListNode{int val;ListNode *next;ListNode(int x) :val(x), next(nullptr){}};void helper(ListNode* head, vector<int> &result){if (head){if (head->next){helper(head->next, result);//注意好好理解这个地方,当最后一次不符合if条件时,执行result.后面的内容。执行完毕后,其实是返回到上一次执行到这里的代码,继续执行result.后面的内容。这里我之前一直没太理解,有空好好研究一下递归的调用过程。与函数调用时现场保护的原则应该是有关系的}//if result.push_back(head->val);}//if int temp = 0;}vector<int> printListFromTailToHead(ListNode* head) {vector<int> result;// 递归实现 helper(head, result);return result;}int main(){ListNode* root = new ListNode(1);ListNode* node1 = new ListNode(2);ListNode* node2 = new ListNode(3);ListNode* node3 = new ListNode(4);ListNode* node4 = new ListNode(5);root->next = node1;node1->next = node2;node2->next = node3;node3->next = node4;vector<int> result = printListFromTailToHead(root);for (int i = 0; i < result.size(); ++i){cout << result[i] << endl;}//for return 0;}思路3的代码:很巧妙利用了每次在vector前端插入,只是我觉得这样的开销可能会比较大啊~~
vector<int> printListFromTailToHead(ListNode* head) {vector<int> result;ListNode* p = head;while (p){result.insert(result.begin(), p->val);p = p->next;}//while return result;}【参考】http://blog.csdn.net/sunnyyoona/article/details/12858771
0 0
- 关于反转链表的问题
- 链表的反转问题
- 关于单向链表的反转
- 一个关于字符串反转的问题;
- 关于NSString字符串反转的问题
- 关于为什么要反转画布的问题
- 关于数组字符反转的问题
- 单向链表反转的问题
- 关于画布反转问题
- 链表反转问题收集
- 数据结构 -链表反转问题
- 链表的反转
- 链表的反转
- 链表的反转
- 链表的反转
- 链表的反转
- 链表的反转
- 链表的反转
- 关于oracle with as用法
- UVa 11059----Maximum Product(最长上升子序列乘积)
- 一些软件工具注册码
- 【RequireJS 学习笔记】RequireJS 学习笔记 1 —— RequireJS 界的 Hello World
- VC解析XML
- 关于反转链表的问题
- Adaboost学习资料
- 如何关闭应用程序
- 动态规划 基础总结
- Android table布局开发的一个简单的计算器
- 倒输一个整数(递归调用)
- 前端优化十四原则
- dedecms后台验证码显示不正常的四种处理办法
- UVa 658 It's not a Bug, it's a Feature! (Dijkstra+位运算技巧+好题)