数据结构基础的头插法
代码如下:
/**
* 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* _head = new ListNode;
ListNode* cur;
while(head!= nullptr){
if(_head->next == nullptr){
cur = head;
head = head->next;
cur->next = nullptr;
_head->next = cur;
}else{
cur = head;
head = head->next;
cur->next = _head->next;
_head->next = cur;
}
}
return _head->next;
}
};