• 剑指offer-从尾到头打印链表


    题目要求

    输入一个链表,从尾到头放入ArrayList并返回。

    C++实现

    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            ListNode *p=head;
            vector<int> ArrayList;
            while(p!=nullptr){
                ArrayList.push_back(p->val);
                p=p->next;
            }
            reverse(ArrayList.begin(),ArrayList.end());
            return ArrayList;
        }
    };
    

    头插vector效率很低,所以采用先push_back,后翻转vector的方式。
    同样的思路使用Python实现如下。

    Python实现

    非递归实现

    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # 返回从尾部到头部的列表值序列,例如[1,2,3]
        def printListFromTailToHead(self, listNode):
            ArrayList=[]
            while listNode is not None:
                ArrayList.append(listNode.val)
                listNode=listNode.next
            ArrayList.reverse()
            return ArrayList
    

    递归实现

    # -*- coding:utf-8 -*-
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution: 
    # 返回从尾部到头部的列表值序列,例如[1,2,3] 
        def printListFromTailToHead(self, listNode): 
            # write code here 
            if listNode is None: 
                return [] 
            return self.printListFromTailToHead(listNode.next) + [listNode.val]
    
    keep going
  • 相关阅读:
    codeforces 673D D. Bear and Two Paths(构造)
    codeforces 673C C. Bear and Colors(暴力)
    codeforces 673B B. Problems for Round(模拟)
    codeforces 673A A. Bear and Game(水题)
    hdu-3555 Bomb(数位dp)
    西交校赛 I. GZP and CS(数位dp)
    西交校赛 F. GZP and Poker
    删除目录下包含“2018” 关键字文件
    CSV转成Excel格式
    解决字符sqlplus 乱码
  • 原文地址:https://www.cnblogs.com/MarkKobs-blog/p/10344500.html
Copyright © 2020-2023  润新知