/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*///1. 迭代-----头插法1class Solution {public:ListNode* reverseList(ListNode* head) {ListNode *prev = nullptr;ListNode *cur = head;while(cur){ListNode *next = cur->next;cur->next = prev;prev = cur;cur = next;/*思路:54321变成12345,后继都变成前驱,所以可以使后继指向自身,之后指针cur后移*/}return prev;}};//2. 迭代---就地逆置class Solution {public:ListNode* reverseList(ListNode* head) {if(!head || !head->next) return head;auto l = head;auto r = l->next;while(r){auto next = r->next;r->next = l;l = r;r = next;}head->next = NULL;return l;}};//3. 递归class Solution {public:ListNode* reverseList(ListNode* head) {if(!head || !head->next) return head;ListNode *cur = reverseList(head->next);head->next->next = head;head->next = nullptr;return cur;}};//4. 迭代,头插法2class Solution {public:ListNode* reverseList(ListNode* head) {//迭代,头插法ListNode *dummy = nullptr;ListNode *cur = head;while(cur){ListNode *next = cur->next;if(!dummy) {dummy = cur;dummy->next = NULL;}else{cur->next = dummy;dummy = cur;}cur = next;}return dummy;}};
递归理解自链接
