反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路:
空间换时间,利用数组把head的数据记录下来,然后再反向遍历数组,生成新的链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if (head == NULL || head->next == NULL)return head;
ListNode* last=head;
ListNode*p = head;
vector<int> num;
while (last)
{
num.push_back(last->val);
last = last->next;
}
while (head)
{
head->val = num.at(num.size() - 1);
num.pop_back();
head = head->next;
}
return p;//这里必须要用额外的指针指住原来的头部位置,要是return head的话,此时head指向NULL,则return的为NULL
}
};