zoukankan      html  css  js  c++  java
  • [剑指OFFER] 从尾到头打印链表

    题目描述

    输入一个链表,从尾到头打印链表每个节点的值。返回新链表的头结点。
     
     
    方法一:用stack,或者最好vector.reverse
            vector<int> printListFromTailToHead(struct ListNode* head)
            {
                stack<int> st;
                vector<int> rtn;
    
                while(head)
                {
                    st.push(head->val);
                    head= head->next;
                }
    
                while(!st.empty())
                {
                    int tmp = st.top();
                    st.pop();
                    rtn.push_back(tmp);
                }
                
                return rtn;
            }

    方法二:递归在本质上就是一个栈结构,于是很自然地想到用递归来实现。要实现反过来输出链表,每访问到一个结点的时候,先递归输出它后面的结点,再输出该结点自身,这样链表的输出结构就反过来了。

            vector<int> printListFromTailToHead1(struct ListNode* head)
            {
                vector<int> rtn;
                print(head, rtn);
                return rtn;
            }
    
            void print(ListNode* head, vector<int> &rtn)
            {
                if(head == NULL)
                    return;
    
                print(head->next, rtn);
                rtn.push_back(head->val);
            }
     
  • 相关阅读:
    golang 用tar打包文件或文件夹
    golang 最和谐的子序列
    golang 轮训加密算法
    golang map
    golang 队列
    golang 栈操作
    golang 多维数组
    golang 数组反转
    c# sendmessage control to scroll
    c# 启动的时候向其他程序传值
  • 原文地址:https://www.cnblogs.com/diegodu/p/4571224.html
Copyright © 2011-2022 走看看