zoukankan      html  css  js  c++  java
  • 剑指Offer——从尾到头打印链表

    题目描述:

    输入一个链表,从尾到头打印链表每个节点的值。

    分析:

    方法1:利用栈的性质,先从头到尾遍历链表每个节点的值存入栈中,最后一个一个出栈顺序便是从尾到头的。

    方法2:直接从头到尾遍历链表存储节点的值将值存到数组中,最后翻转数组。

    方法3:直接从头到尾遍历链表存储节点的值将值插入到数组的第一个位置。

    方法4:递归,返回链表下一节点往下遍历的结果加上当前节点的值组成的结果。

    方法1代码:

     1 /**
     2 *  struct ListNode {
     3 *        int val;
     4 *        struct ListNode *next;
     5 *        ListNode(int x) :
     6 *              val(x), next(NULL) {
     7 *        }
     8 *  };
     9 */
    10 class Solution {
    11 public:
    12     vector<int> printListFromTailToHead(ListNode* head) {
    13         stack<int> myStack;
    14         ListNode* p = head;
    15         while(p) {
    16             myStack.push(p->val);
    17             p = p->next;
    18         }
    19         vector<int> res;
    20         while(!myStack.empty()) {
    21             res.push_back(myStack.top());
    22             myStack.pop();
    23         }
    24         return res;
    25     }
    26 };

    递归解法:

     1 /**
     2 *  struct ListNode {
     3 *        int val;
     4 *        struct ListNode *next;
     5 *        ListNode(int x) :
     6 *              val(x), next(NULL) {
     7 *        }
     8 *  };
     9 */
    10 class Solution {
    11 public:
    12     vector<int> res;
    13     vector<int> printListFromTailToHead(ListNode* head) {
    14         if(head) {
    15             res = printListFromTailToHead(head->next);
    16             res.push_back(head->val);
    17             return res;
    18         }
    19         return res;
    20     }
    21 };
  • 相关阅读:
    回顾python,就当做笔记了
    测试知识回顾
    转发 Python接口自动化
    性能测试脚本调优
    java
    新的一年,希望自己有所提升,在这简单的记录,自己的学习。
    navicat 连接 mysql 出现Client does not support authentication protocol requested by server解决方案
    tomcat context配置
    tomcat host 配置
    flyway使用
  • 原文地址:https://www.cnblogs.com/jacen789/p/7737780.html
Copyright © 2011-2022 走看看