题目

输入一个链表,反转链表后,输出新链表的表头。

思路

没有有递归也没有用迭代,显示将每个结点存储在vector数组里,然后反向构建链表,输出头节点。

代码

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (!pHead)
        {
            return nullptr;
        }
        vector<ListNode *> list;
        ListNode* pLinked=pHead;
        while (pLinked->next != NULL)
        {
            list.push_back(pLinked);
            pLinked = pLinked->next;
        }
        list.push_back(pLinked);
        pLinked = list[list.size()-1];
        pHead = pLinked;
        for (int i = list.size()-2; i >= 0; i--)
        {
            pLinked->next = list[i];
            pLinked = pLinked->next;
        }
        pLinked->next = NULL;
        return pHead;
    }
};