- 链表节点的头插
/**
* 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) {
ListNode *newHead = nullptr,*nxt;
while(head){
nxt = head->next;
head->next = newHead;
newHead = head;
head = nxt;
}
return newHead;
}
};
- 递归
/**
* 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 || !head->next) return head;
ListNode* res = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return res;
}
};