剑指offer 从尾到头打印链表
来源:互联网 发布:手游数据查询 编辑:程序博客网 时间:2024/06/02 06:34
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
思路
总共有五种方法,如下:
1. 将原链表的值存在一个栈中,然后再将栈输出到另一个vector数组里。
2. 直接将原链表的值存在一个vector数组里,最后reverse翻转一下。
3. 每插入一个,都放到最前面,复杂度是
4. 通过递归到最后一个值,再一层一层输入到vector数组里。
5. 直接将链表翻转。
代码
- 1.
class Solution {public: vector<int>printListFromTailToHead(ListNode*head) { int digit; stack<int> f; vector<int> res; ListNode *t = head; while(t != NULL) { f.push(t->val); t = t->next; } while(!f.empty()) { digit = f.top(); f.pop(); res.push_back(digit); } return res; }};
- 2.
class Solution {public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> res; while(head != NULL) { res.push_back(head->val); head = head->next; } reverse(res.begin(),res.end()); return res; }};
- 3.
class Solution {public: vector<int> printListFromTailToHead(struct ListNode* head) { vector<int> res; if(head != NULL) { while(head != NULL) { res.insert(res.begin(),head->val); head = head->next; } } return res; }};
- 4.
class Solution {public: vector<int> res; vector<int> printListFromTailToHead(ListNode* head) { if(head!=NULL){ printListFromTailToHead(head->next); res.push_back(head->val); } return res; }};
- 5.
class Solution {public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> res; ListNode *pre = NULL; ListNode *p = NULL; while(head != NULL) { p = head->next; //p为head的下一个节点 head->next = pre;//指向前一个节点 pre = head;//向后移动 head = p;//向后移动 } while(pre != NULL) { res.push_back(pre->val); pre = pre->next; } return res; }};
阅读全文
0 0
- 剑指offer:5-从尾到头打印链表
- [剑指Offer]7.从尾到头打印链表
- 剑指offer:从尾到头打印链表
- 从尾到头打印链表--《剑指offer》
- 剑指Offer:从尾到头打印链表
- 【剑指offer】从尾到头打印链表
- 【剑指offer】Q5:从尾到头打印链表
- 剑指Offer之从尾到头打印链表
- 剑指offer系列源码-从尾到头打印链表
- 剑指offer 05: 从尾到头打印链表
- 剑指offer--从尾到头打印链表
- 剑指offer-5 从尾到头打印链表
- 剑指Offer之 - 从尾到头打印链表
- 剑指offer 5 -从尾到头打印链表
- 剑指offer: 从尾到头打印链表(链表)
- 《剑指Offer》面试题:从尾到头打印链表
- 剑指offer:从尾到头打印链表
- 剑指offer:从尾到头打印链表代码实现
- CCF-训练50题-NO.2-图像旋转问题
- tf.identity的意义以及用例
- HDFS JAVA API操作
- iOS 常用的宏定义
- NUIST OJ 1350-1352 面朝大海,春暖花开【初识线段树】
- 剑指offer 从尾到头打印链表
- Python数据类型:列表
- for 创建一个方法:键盘录入一个数 ,求它的 阶乘 及 阶乘的和
- GoldenGate 传统抽取进程随 DataGuard 主备快速切换的方案(ADG 模式)
- [POJ] 2528
- java注解
- Ubuntu 16.04 (linux)下MySQL的安装
- Thread和Runnable之间的关系
- js为li列表添加点击事件