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 };
  • 相关阅读:
    88. Merge Sorted Array
    87. Scramble String
    86. Partition List
    85. Maximal Rectangle
    84. Largest Rectangle in Histogram
    [Windows] Diskpart Scripts and Examples
    [Windows] 对于 mount 到文件夹路径下的分区,也可以使用 GetDiskFreeSpaceExA 函数
    [Windows] DiskPart commands
    [Windows] 如何用编程的方式格式化硬盘
    Windows API Index
  • 原文地址:https://www.cnblogs.com/jacen789/p/7737780.html
Copyright © 2011-2022 走看看