//输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 // // // // 示例 1: // // 输入:head = [1,3,2] //输出:[2,3,1] // // // // 限制: // // 0 <= 链表长度 <= 10000 // //leetcode submit region begin(Prohibit modification and deletion) import java.util.ArrayList; import java.util.List; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int[] reversePrint(ListNode head) { List<Integer> list = new ArrayList<>(); while (head!=null){ list.add(head.val); head = head.next; } int [] in = new int[list.size()]; for (int i = list.size()-1; i >= 0 ; i--) { in[(list.size()-i-1)] = list.get(i); } return in; } } //leetcode submit region end(Prohibit modification and deletion)
用了三种办法来做了,其他两种都不太理想:
第二种
static public int[] reversePrint(ListNode head) { StringBuffer sb = new StringBuffer(); while (head!=null){ sb.append(head.val); head = head.next; } int [] in = new int[sb.length()]; // for (int i = sb.length()-1; i >= 0; i--) { // System.out.println("a="+sb.charAt(i)+"---->"+(sb.length()-i-1)); // } for (int i = sb.length()-1; i >= 0 ; i--) { in[(sb.length()-i-1)] = Integer.valueOf(String.valueOf(sb.charAt(i))); } return in; }
第三种
public int[] reversePrint1(ListNode head) { String s = ""; while (head!=null){ s = s +head.val + ","; head = head.next; } s = s.substring(0,s.length()-1); //去掉最后一个空格。 String[] split = s.split(","); for (int i = 0; i < split.length; i++) { } int [] in = new int[split.length]; int j = 0; for (int i = split.length-1; i >= 0 ; i--) { in[j] = Integer.valueOf(split[i]); j++; } return in; }