输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路1
如果允许更改结构, 那么可以先把链表反转,在顺序打印,此时不需额外的空间
class Solution {
public int[] reversePrint(ListNode head) {
if (head == null) return new int[0];
ListNode tmp = head;
ListNode next = tmp.next;
tmp.next = null;
int size = 1;
while (tmp != null && next != null) {
ListNode tt = next.next;
next.next = tmp;
tmp = next;
next = tt;
size++;
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = tmp.val;
tmp = tmp.next;
}
return result;
}
}
反转链表的经典操作
ListNode tmp = head;
ListNode next = tmp.next;
tmp.next = null;
while (tmp != null && next != null) {
ListNode nn = next.next;
next.next = tmp;
tmp = next;
next = nn;
}
思路2
如果不允许修改链表,那么可以使用一个栈来存储节点,然后先入后出,同时由栈可以想到递归,递归本身也是一个栈.
class Solution {
public int[] reversePrint(ListNode head) {
if (head == null) return new int[0];
int size = 0;
ListNode tmp = head;
while(tmp != null) {
size++;
tmp = tmp.next;
}
int[] result = new int[size];
// 开始递归
tmp = head;
recur(result, tmp, size - 1);
return result;
}
private void recur(int[] result, ListNode node, int index) {
if (node == null) return;
recur(result, node.next, index - 1);
result[index] = node.val;
}
}