题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
解题思路
- 先顺序遍历一遍,并将每个元素添加到数组中;
- 之后,将数组进行反转,并返回该结果。
Python
class Solution: def printListFromTailToHead(self , listNode: ListNode) -> List[int]: res = [] while listNode != None: res.append(listNode.val) listNode = listNode.next return res[::-1]
C++
技术点:
- 运用到了reverse函数。
- reverse函数可以反转一个容器中的内容,包含在<algorithm>库中。
- reverse循环交换首尾元素,循环半个数组长度,复杂度是线性的,O(N)。
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> res; while(head) { res.push_back(head->val); head = head->next; } reverse(res.begin(), res.end()); return res; } };