输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
方法一:递归
python:
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
方法二:辅助栈
python:
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
arr = []
while head != None:
arr.append(head.val)
head = head.next
return arr[::-1]
java:
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> arr = new LinkedList<>();
while(head!=null){
arr.addLast(head.val);
head = head.next;
}
int[] res = new int[arr.size()];
for(int i = 0;i<res.length;i++){
res[i] = arr.removeLast();
}
return res;
}
}
c:逆序赋值。
int* reversePrint(struct ListNode* head, int* returnSize){
int total=0,index=0;
struct ListNode *p=head;
int *res = malloc(10000 * sizeof(int));
memset(res, 0, 10000 * sizeof(int));
while(p){
total++;
p=p->next;
}
index = total;
p=head;
while(p){
res[--index]=p->val;
p=p->next;
}
(*returnSize) = total;
return res;
}