题目描述
开始以为能用Stack,后面发现不行。(是默认添加相关类?)
Java 代码不使用栈
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] printListReversingly(ListNode head) {
ListNode p = head;
int count = 0;
while (p != null){
p = p.next;
count++;
}
int[] result = new int[count];
p = head;
for (int i = count - 1; i >= 0; i--) {
result[i] = p.val;
p = p.next;
}
return result;
}
}
Java 代码使用栈
public int[] printListReversingly(ListNode head) {
Stack<Integer> stack = new Stack<>();
ListNode p = head;
int count = 0;
while (p != null){
stack.push(head.val);
p = p.next;
count++;
}
int[] result = new int[count];
for (int i = 0; i < result.length; i++) {
result[i] = stack.pop();
}
return result;
}