解法一:用前插法新建链表:
/**
* 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) {
ListNode *m_reverse = new ListNode;
m_reverse->next = NULL;
ListNode *r = m_reverse;
while(head!=NULL)
{
ListNode *p = new ListNode;
p->val = head->val;
p->next = m_reverse->next;
m_reverse->next = p;
head = head->next;
}
return m_reverse->next;
}
};
解法二:用双指针法反转next指向
/**
* 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) {
ListNode *m_reverse = head;
ListNode *pre = NULL;
ListNode *TempList = NULL;
while(m_reverse)
{
TempList = m_reverse->next;
m_reverse->next = pre;
pre=m_reverse;
m_reverse = TempList;
}
return pre;
}
};