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

    题目描述

    输入一个链表,从尾到头打印链表每个节点的值。
     
     
    思路1:stack
     
     1 import java.util.ArrayList;
     2 import java.util.Stack;
     3 public class Solution {
     4     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
     5         Stack<Integer> s=new Stack<Integer>();
     6         for(ListNode l = listNode;l!=null;l=l.next)
     7             s.push(l.val);
     8         ArrayList<Integer> newlist = new ArrayList<Integer>();
     9         while(!s.isEmpty()){
    10             newlist.add(s.pop());
    11         }
    12         return newlist;
    13     }
    import java.util.ArrayList;
    import java.util.Stack;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode head) {
            Stack<Integer>  s = new Stack<Integer>();
            for(;head!=null;head = head.next)
                s.push(head.val);
            ArrayList<Integer> list = new ArrayList<Integer>();
            for( int item : s)
                list.add(item);
             return list;
        }
    }

    迭代返回的是无序的!!!!!!!!

    20180303

     1 # -*- coding:utf-8 -*-
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution:
     8     # 返回从尾部到头部的列表值序列,例如[1,2,3]
     9     def printListFromTailToHead(self, root):
    10         # write code here
    11         res = []
    12         while root!=None:
    13             res.append(root.val)
    14             root = root.next
    15         return res[::-1]
  • 相关阅读:
    c++——类 继承
    Pytorch Tensor, Variable, 自动求导
    Python-OpenCV实现二值图像孔洞填充
    神经网络手写数字识别numpy实现
    神经网络反向传播公式推导
    转:Markdown语法大全
    markdown居中对齐,左对齐,右对齐
    硬编码与软编码
    转:Markdown数学公式语法
    Python if __name__=='__main__'
  • 原文地址:https://www.cnblogs.com/zle1992/p/7751586.html
Copyright © 2011-2022 走看看