从尾到头打印链表

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

 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 __init__(self):
10         self.result = []
11         
12     def track(self,listNode):
13         if listNode.next:
14             self.track(listNode.next)
15         self.result.append(listNode.val)
16             
17     def printListFromTailToHead(self, listNode):
18         if listNode:
19             self.track(listNode)
20         return self.result
21         # write code here


leetcode地址,Java版代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public int[] reversePrint(ListNode head) {
11         Stack<Integer> stack = new Stack<>();
12         int len = 0;
13         while (head != null) {
14             stack.add(head.val);
15             head = head.next;
16             len++;
17         }
18         int[] ret = new int[len];
19         int i = 0;
20         while (!stack.isEmpty()){
21             ret[i++] = stack.pop();
22         }
23         return ret;
24     }
25 }

 

Java第二种方式:

 1 class Solution {
 2     public int[] reversePrint(ListNode head) {
 3         ArrayList<Integer> al = new ArrayList<Integer>();
 4         while(head != null){
 5             al.add(head.val);
 6             head = head.next;
 7         }
 8         Collections.reverse(al);
 9         return al.stream().mapToInt(Integer::valueOf).toArray();
10     }
11 }

 

C#语法:

 1 public class Solution {
 2     public int[] ReversePrint(ListNode head)
 3         {
 4             var al = new List<int>();
 5             while(head != null)
 6             {
 7                 al.Add(head.val);
 8                 head = head.next;
 9             }
10             al.Reverse();
11             return al.ToArray();
12         }
13 }

 

posted on 2019-06-12 22:01  Sempron2800+  阅读(88)  评论(0编辑  收藏  举报