zoukankan      html  css  js  c++  java
  • 【算法编程 C++ python】单链表反序输出

    题目描述

    输入一个链表,从尾到头打印链表每个节点的值。
     
    以下方法仅仅实现了功能,未必最佳。在牛客网测试,
    C++:3ms 480k
    Python:23ms 5732k
    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector<int> vec_output;
            if (head == NULL){return vec_output;}
            do{
                vec_output.push_back(head->val);
                head = head->next;
            }while(head!=NULL);
            reverse(vec_output.begin(),vec_output.end());
            return vec_output;
        }
    };

    Python:

    # -*- coding:utf-8 -*-
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # 返回从尾部到头部的列表值序列,例如[1,2,3]
        def printListFromTailToHead(self, listNode):
            list_val = []
            while(True):
                if listNode == None: return [] 
                list_val.append(listNode.val)
                if (listNode.next):
                    listNode = listNode.next
                else:
                    break
            return list_val[::-1] 
  • 相关阅读:
    C# 导入Excel遇到数字字母混合列数据丢失解决
    C# 导出 Excel
    DataGridView 改变行列颜色
    EditPlus使用技巧
    jquery的事件与应用
    jquery操作DOM元素的复习
    jquery笔记
    jquery 和ajax
    jQuery笔记
    CSS相关知识三
  • 原文地址:https://www.cnblogs.com/xiangfeidemengzhu/p/8975034.html
Copyright © 2011-2022 走看看