06从尾到头打印链表

题目描述:

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

 

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

想用栈的方法来实现,可是我目前还没有做很多栈的题,水平有限

以下是我写的错误的栈的代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

 struct stack
{
    int val;
    struct ListNode *top;
};
int* reversePrint(struct ListNode* head, int* returnSize){
//如果能用栈来解决的话 会容易很多
int stack[1000000];
struct ListNode *p=head;
while(p!=NULL)
{
    stack.push(p->val);
    p=p->next;
}
while(stack!=empty)
{
    stack[i]=stack.pop(stack.top());
    stack.pop();
}
return 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){
//如果能用栈来解决的话 会容易很多

struct ListNode *p=head;
int *a=(int *)malloc(sizeof(int)*10000);
int n=0;//计算出链表大小
while(p!=NULL)
{
   n++;
   p=p->next;
}
*returnSize=n;
p=head;
while(n--)
{
    a[n]=p->val;
    p=p->next;
}
return a;
}

  反思;

这个方法并不算是一个优秀的方法,我希望后面做到栈的时候能在回头把这道题重新做一下

原文地址:https://www.cnblogs.com/redzzy/p/13343971.html