剑指offer15-翻转链表

题目描述

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

思路:遍历链表,将数值存储到数组中。然后再将数组中的值反向复制到链表

代码:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) { 
        //若是没有这个if判断,就会出现内存不够,栈溢出等问题
        if(pHead==NULL)
            return NULL;
        ListNode* p = pHead; 
        vector<int> arr;
        arr.push_back(p->val);
        while(p->next!=NULL)
        {
            p=p->next;
            arr.push_back(p->val);
        }
        int len = arr.size();
        p=pHead;
        for(int i=len-1;i>=0;i--)
        {
            p->val = arr[i];
            p=p->next;
        }
        return pHead;

    }
};
原文地址:https://www.cnblogs.com/loyolh/p/12347075.html