3 从尾到头打印链表
2017-10-29 22:11
246 查看
题目描述
输入一个链表,从尾到头打印链表每个节点的值。思路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; } }
迭代返回的是无序的!!!!!!!!
201803031 # -*- 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]
相关文章推荐
- 《苦练算法》-剑指Offer- 三、 从尾到头打印链表 -python编写
- [剑指offer]从尾到头打印链表
- Offer5 从尾到头打印链表
- 剑指offer之从尾到头打印链表
- 输入一个链表,从尾到头打印链表每个节点的值。
- 剑指offer-从尾到头打印链表-php
- 【剑指offer】面试题五:从尾到头打印链表
- 剑指offer_面试题5_从尾到头打印链表(栈和递归实现)
- 从尾到头打印链表
- 剑指offer 从尾到头打印链表
- [剑指offer]面试题5:从尾到头打印链表
- 剑指offer——从尾到头打印链表节点的值
- 从尾到头打印链表
- 输入一个链表,从尾到头打印链表每个节点的值
- C语言实现 从尾到头打印链表每个节点的值(链表学习 二)
- 题目1511:从尾到头打印链表-九度
- 【剑指offer】从尾到头打印链表
- 从尾到头打印链表
- 递归从尾到头打印链表每个节点的值
- 算法题目-从尾到头打印链表