剑指 Offer 06. 从尾到头打印链表题解

题目链接

题目大意:给出一个单链表,返回一个逆序的 vector

我的思路是先将链表逆序,然后遍历添加到 vector 中。

代码:

#include <bits/stdc++.h>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        ListNode *prev = NULL, *next;
        while (head != NULL) {
            next = head->next;
            head->next = prev;
            prev = head;
            head = next;
        }

        vector<int> v;
        head = prev;
        while (head != NULL) {
            v.push_back(head->val);
            head = head->next;
        }

        return v;
    }
};

int main(void) {

    ListNode* l1 = new ListNode(1);
    ListNode* l2 = new ListNode(3);
    ListNode* l3 = new ListNode(2);

    l1->next = l2;
    l2->next = l3;
    l3->next = NULL;

    Solution s;
    vector<int> v = s.reversePrint(l1);
    for (auto i : v) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页