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]

 

posted @ 2017-10-29 22:11  乐乐章  阅读(117)  评论(0编辑  收藏  举报