题目

题解
第一想法
有点像前边儿的反转链表,但是这里是用数组返回。这样的话用栈来做就可以了。
首先创建一个数组stack,将原数组压入栈中。然后再创建一个数组ret,将stack的元素按顺序出栈保存在ret里,即可实现从尾到头。此处记得free前面的stack。
正确题解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
int* stack = (int*)malloc(sizeof(int) * 10000);
int top = 0;
while(head){
stack[top++] = head -> val;
head = head -> next;
}
int* ret = (int*)malloc(sizeof(int) * 10000);
*returnSize = 0;
while(top--){
ret[(*returnSize)++] = stack[top];
}
free(stack);
return ret;
}
该文章介绍了一种使用栈来反转链表并按顺序返回数组的方法。首先将链表元素压入栈中,然后依次出栈存入新数组,从而实现从尾到头的顺序。最后释放栈的空间,返回反转后的数组。
646

被折叠的 条评论
为什么被折叠?



