zoukankan      html  css  js  c++  java
  • [NewCode 5] 从尾到头打印链表

    题目描述

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

    题目比较水,一遍就 AC 了,来看代码:

    /**
    *  struct ListNode {
    *	    int val;
    *	    struct ListNode *next;
    *	    ListNode(int x) :
    *			  val(x), next(NULL) {
    *	    }
    *  };
    */
    class Solution {
    public:
    	vector<int> printListFromTailToHead(struct ListNode *head) {
    		vector<int> ret;
            printListFromTailToHead_help(head, ret);
            return ret;
    	}
        
    private:
        void printListFromTailToHead_help(struct ListNode *head, vector<int> &ret) {
            if (head == NULL) {
                return;
            }
            
            printListFromTailToHead_help(head->next, ret);
            ret.push_back(head->val);
        }
    };

    使用递归写起来就是简单,但是当链表非常长的时候,就会导致函数调用的层级较深,有可能会导致栈溢出,如下版本为非递归形式:

    /**
    *  struct ListNode {
    *	    int val;
    *	    struct ListNode *next;
    *	    ListNode(int x) :
    *			  val(x), next(NULL) {
    *	    }
    *  };
    */
    class Solution {
    public:
    	vector<int> printListFromTailToHead(ListNode* head) {
    		stack<ListNode *> stkNodes;
            while (head) {
                stkNodes.push(head);
                head = head->next;
            }
            
            vector<int> ret;
            while (!stkNodes.empty()) {
                ret.push_back(stkNodes.top()->val);
                stkNodes.pop();
            }
            
            return ret;
    	}
    };

    其实,还有更无耻的方法也可以AC,就是按顺序压入vector中,最后使用迭代器反转一下,但是不建议使用这种方法:

    /**
    *  struct ListNode {
    *	    int val;
    *	    struct ListNode *next;
    *	    ListNode(int x) :
    *			  val(x), next(NULL) {
    *	    }
    *  };
    */
    class Solution {
    public:
    	vector<int> printListFromTailToHead(ListNode* head) {
    		vector<int> ret;
            while (head) {
                ret.push_back(head->val);
                head = head->next;
            }
            
            reverse(ret.begin(), ret.end());
            return ret;
    	}
    };
  • 相关阅读:
    CF1552 D. Array Differentiation
    CF1542 B. Plus and Multiply
    CF1543 D1. RPD and Rap Sheet (Easy Version)
    CF1555 E. Boring Segments(线段树+双指针)
    CF1513 D. GCD and MST
    hdu 6194 string string string
    CF1527 B2. Palindrome Game (hard version)
    DDD领域驱动设计落地实践(十分钟看完,半小时落地)
    【5分钟】W10 64bit系统本地安装postgresql 11
    程序员如何成为架构师
  • 原文地址:https://www.cnblogs.com/jianxinzhou/p/4492705.html
Copyright © 2011-2022 走看看