题目要求:
输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
数据范围
0≤0≤ 链表长度 ≤1000≤1000。
样例
输入:[2, 3, 5]
返回:[5, 3, 2]
思路分析:
根据链表只能往后查找的特点,要注意先保存好头结点,然后通过遍历得到节点数,最后对数组逆序赋值。
ac代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* Note: The returned array must be malloced, assume caller calls free().
*/
int* printListReversingly(struct ListNode* head) {
if(head == NULL) return NULL;
int cnt = 0, * arr;
struct ListNode *p;
p = head;
//无头结点链表,有val值的结点个数等于结点个数
while(p) {
++cnt;
p = p->next;
}
arr = (int*)malloc(cnt * sizeof(int));
while(head){
arr[--cnt] = head->val;//这里注意数组下标从0开始,所以是--cnt,而不是cnt--
head = head->next;
}
return arr;//返回首地址
}