/**
* 自己的代码,先反转链表,再构造数组并遍历填上节点值
* 执行用时:0 ms, 在所有 Java 提交中击败了100.00%
* 内存消耗:38.9 MB, 在所有 Java 提交中击败了75.55%
*/
class Solution {
public int[] reversePrint(ListNode head) {
ListNode sentinel = new ListNode(-1), p = head;
int cnt = 0;
while (p != null) {
ListNode next = p.next;
p.next = sentinel.next;
sentinel.next = p;
p = next;
cnt++;
}
p = sentinel.next;
int[] res = new int[cnt];
for (int i = 0; i < cnt; i++, p = p.next) {
res[i] = p.val;
}
return res;
}
}
/**
* 递归反转链表并记录长度,再构造结果数组
* 执行用时:0 ms, 在所有 Java 提交中击败了100.00%
* 内存消耗:39.7 MB, 在所有 Java 提交中击败了13.02%
*/
class Solution {
public int[] reversePrint(ListNode head) {
if (head == null) {
return new int[0];
}
int[] cnt = new int[1];
ListNode newHead = helper(head, cnt);
int[] res = new int[cnt[0]];
for (int i = 0; i < cnt[0]; i++, newHead = newHead.next) {
res[i] = newHead.val;
}
return res;
}
private ListNode helper(ListNode head, int[] cnt) { // reverse list recursively, and count the nodes
cnt[0]++;
if (head.next == null) {
return head;
}
ListNode newHead = helper(head.next, cnt);
head.next.next = head;
head.next = null;
return newHead;
}
}
/**
* 也可以不用重构反转的链表,用栈得到size和倒序的节点
* 执行用时:1 ms, 在所有 Java 提交中击败了73.99%
* 内存消耗:39 MB, 在所有 Java 提交中击败了63.80%
*/
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<ListNode> stack = new LinkedList();
ListNode p = head;
while (p != null) {
stack.push(p);
p = p.next;
}
int[] res = new int[stack.size()];
for (int i = 0; !stack.isEmpty(); i++) {
res[i] = stack.pop().val;
}
return res;
}
}