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

    输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

    ===============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):
            # write code here
            if not listNode:
                return []
            res = []
            while listNode:
                res.append(listNode.val)
                listNode = listNode.next
            return res[::-1]

    ==============Java============

    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            ArrayList<Integer> res = new ArrayList<>();
            if (listNode == null) {
                return res;
            }
            addList(res, listNode);
            return res;
        }
        public void addList(ArrayList<Integer> res, ListNode listNode) {
            if (listNode != null){
                addList(res, listNode.next);
                res.add(listNode.val);
            }
        }
    }
  • 相关阅读:
    2015 多校联赛 ——HDU5389(dp)
    spring MVC配置详解
    面试题整理11
    面试题整理09
    Spring和SpringMVC的区别
    SpringMVC01
    js中typeof与instanceof用法小记
    Java 可变参数
    log4j文件的配置
    Hibernate 分组查询 子查询 原生SQL
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13537863.html
Copyright © 2011-2022 走看看