题目描述
输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回结果用数组存储。
样例
Input: [2,3,5]
Output: [5,3,2]
解题思路
-
描述
遍历链表并使用vector存储,翻转该数组,返回即可。 -
实现代码:
/* 使用到的头文件 #include <vector> 结构体 struct ListNode { int val; struct ListNode *next; ListNode(int val) { this->val = val; this->next = NULL; } }; */ vector<int> printListReversingly(ListNode* head) { vector<int> result; //存放结果 ListNode *p; for (p = head->next; p != NULL; p = p->next) //遍历链表 { result.push_back(p->val); } return vector<int>(result.rbegin(), result.rend()); //使用vector的构造函数返回 }