题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> arr;
while(head)
{
arr.insert(arr.begin(), head->val);
head = head->next;
}
return arr;
}
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> arr;
while(head)
{
arr.insert(arr.begin(), head->val);
head = head->next;
}
return arr;
}
};
如上,利用 vector自带的insert()函数,将ListNode遍历到的元素都往前面插入,该数组就成为了链表从尾到头的打印啦
#数据结构编程链表#