輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution {
public int[] reversePrint(ListNode head) {
/*
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
int[] arr = new int[stack.size()];
for(int i = 0; i < arr.length; i++){
arr[i] = stack.pop();
}
return arr;
*/
int len = 0;
ListNode cur = head;
while(cur != null){
len++;
cur = cur.next;
}
int[] arr = new int[len];
for(int i = len - 1; i >= 0; i--){
arr[i] = head.val;
head = head.next;
}
return arr;
}
/* 反轉鏈表
public ListNode revListNode(ListNode head) {
ListNode cur = head;
ListNode prev = null;
while(cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return cur;
}
*/
}