NC265. 从尾到头打印链表
描述
示例1
输入:
{1,2,3}
输出:
[3,2,1]
示例2
输入:
{67,0,24,58}
输出:
[58,24,0,67]
C++ 解法, 执行用时: 3ms, 内存消耗: 804KB, 提交时间: 2021-09-18
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { ListNode *p = head; int len = 0; if (head == NULL) { return {}; } while (p) { p = p->next; len++; } vector<int> nums(len); p = head; for (int i = len - 1; i >= 0; i--) { nums[i] = p->val; p = p->next; } return nums; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 812KB, 提交时间: 2021-09-22
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { ListNode*p=head; int len=0; if(head==NULL) { return {}; } while(p!=NULL) { p=p->next; len++; } vector<int>arr(len); p=head; for(int i=len-1;i>=0;i--){ arr[i]=p->val; p=p->next; } return arr; } };
C++ 解法, 执行用时: 3ms, 内存消耗: 812KB, 提交时间: 2021-09-12
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> res; res.reserve(10000); while (head) { res.push_back(head->val); head = head->next; } reverse(res.begin(), res.end()); return res; } };
C 解法, 执行用时: 3ms, 内存消耗: 816KB, 提交时间: 2021-11-19
int* printListFromTailToHead(struct ListNode* listNode, int* returnSize ) { if(listNode==NULL) return -1; int *res = NULL; struct ListNode* p = listNode; int num = 0; while(p){ p = p->next; num++; } res = (int*)malloc(num*sizeof(int)); p = listNode; *returnSize = num; while(p){ res[--num] = p->val; p = p->next; } // write code here return res; }
C++ 解法, 执行用时: 3ms, 内存消耗: 896KB, 提交时间: 2022-02-10
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> ans; // 从头节点开始进行遍历 while(head){ // 将每个节点的权值放入动态数组里面 ans.push_back(head->val); // 指针后移动 head=head->next; } // 反转整个数组 reverse(ans.begin(),ans.end()); return ans; } };