剑指 Offer 06. 从尾到头打印链表
题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
本文采用的解法:一、JavaScript利用接口unshift【迭代】 二、Java
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
一、JavaScript(迭代)

1 /** 2 * @param {ListNode} head 3 * @return {number[]} 4 * 将每个结点的值从数组头依次塞进(unshift方法)数组,最后返回 5 */ 6 var reversePrint = function(head) { 7 let num = []; 8 let index = head; 9 while(index !== null) { 10 num.unshift(index.val); 11 index = index.next; 12 } 13 return num; 14 };
二、Java

1 import java.util.*; 2 /** 3 * @author 不乏理想的三师弟 4 */ 5 public class Solution { 6 /** 7 * 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 8 */ 9 10 // 解法一 11 public int[] reversePrint1(ListNode head) { 12 ArrayList<Integer> list = new ArrayList<>(); 13 while(head != null) { 14 list.add(head.val); 15 head = head.next; 16 } 17 18 int length = list.size(); 19 int[] results = new int[length]; 20 int i = 0; 21 while(length > 0) { 22 results[i++] = list.get(--length); 23 } 24 return results; 25 } 26 // 解法二 27 public int[] reversePrint(ListNode head) { 28 int length = 0; 29 ListNode index = head; 30 while(index != null) { 31 index = index.next; 32 length++; 33 } 34 35 int[] results = new int[length]; 36 while(head != null) { 37 results[--length] = head.val; 38 head = head.next; 39 } 40 return results; 41 } 42 } 43 44 class ListNode { 45 int val; 46 ListNode next; 47 48 ListNode(int x) { 49 val = x; 50 } 51 }

浙公网安备 33010602011771号