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 };
  • 相关阅读:
    文学-人物-苏轼:百科
    文学-人物:王维
    文学-人物:杜甫
    文学-人物:李白
    模型-CMM:百科
    公司-魏桥:百科
    云:VMware
    postfix
    CSS 实现背景图尺寸不随浏览器缩放而变化
    Java中线程的操作状态
  • 原文地址:https://www.cnblogs.com/jacen789/p/7737780.html
Copyright © 2011-2022 走看看