题目给出一个链表的头节点,从尾到投返回每一个节点的值,并用数组返回,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
ListNode *curr = head; //建立当前节点
ListNode *prev = NULL; //建立当前节点前一个节点
int n = 0; //n记录节点个数
while(curr && curr != nullptr)
{ //翻转链表
ListNode *NextNode = curr -> next;
curr -> next = prev;
prev = curr;
curr = NextNode;
n += 1;
}
vector<int> temp(n,0); //建立一个数组
for(int i = 0; i <= n-1; i++)
{
temp[i] = prev -> val;
prev = prev -> next;
}
return temp;
}
};