头插法
/**
* 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)
return NULL;
auto dummy = new ListNode(-1);
while(head){
auto p = head->next;
head->next = dummy->next;
dummy->next = head;
head = p;
}
return dummy->next;
}
}
迭代
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)
return head;
auto a = head;
auto b = head->next;
auto c = b->next;
while(b){
c = b->next;
b->next = a;
a = b ;
b = c;
}
head->next = NULL;
return a;
}