leetcode第206题反转链表
方法一:暴力法
最暴力的方法,把链表的数字存到数组里,反转数组,然后把数组里的数一个个加到链表里
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr)
return nullptr;
vector<int> temp;
ListNode* tempNode=head;
while(tempNode!=nullptr)
{
temp.push_back(tempNode->val);
tempNode=tempNode->next;
}
reverse(temp.begin(),temp.end());
tempNode=head;
for(int i=0;i<temp.size();i++)
{
ListNode* node=new ListNode(temp[i]);
tempNode->next=node;
tempNode=tempNode->next;
}
return head->next;
}
};