zoukankan      html  css  js  c++  java
  • 3从尾到头打印链表

    题目描述

    输入一个链表,从尾到头打印链表每个节点的值。
     
    思路:反过来的方法使用stack就可以,或者使用递归方法实现。
    链表指向下一个使用next指针,不要直接使用++pointer的操作。因为链表不一定是连续存储的。
    1.stack
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector<int> result;
            if(head == nullptr){
                return result;
            }
            stack<int> s;
            ListNode* pHead = head;
            while(pHead != nullptr){
                s.push(pHead -> val);
                pHead = pHead -> next;
            }
            int sz = s.size();
            for(int i = 0;i < sz;++i){
                result.push_back(s.top());
                s.pop();
            }
            return result;
        }
    };

    2、递归

    class Solution {
    public:
        void helper(ListNode* head,vector<int> &result){
            if(head == nullptr){
                return;
            }
             
            helper(head -> next,result);
            result.push_back(head -> val);//一定要把位置放在这里
        }
        vector<int> printListFromTailToHead(ListNode* head) {
            vector<int> result;
            if(head == nullptr){
                return result;
            }
            helper(head,result);
            return result;
        }
    };
  • 相关阅读:
    程序崩溃访问非法内存
    C# IP转换,时间转换
    _heap_alloc_dbg 崩溃
    TaskIcon 系统任务栏图标
    zlib 压缩使用
    桌面清理工具
    CMMI知识库(精简版)
    JAVA程序员面试题集合
    OracleDECODE用法
    Oracle索引重建
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7881341.html
Copyright © 2011-2022 走看看