从尾到头打印链表
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<Integer>();
while(head != null) {
stack.addLast(head.val);
head = head.next;
}
int[] result = new int[stack.size()];
for(int i = 0; i < result.length; i++)
result[i] = stack.removeLast();
return result;
}
}
class Solution {
public int[] reversePrint(ListNode head) {
ListNode cur = head;
int count = 0;
while (cur != null) {
cur = cur.next;
count++;
}
int[] array = new int[count];
cur = head;
count--;
while (cur != null && count >= 0) {
array[count--] = cur.val;
cur = cur.next;
}
return array;
}
}
|