解答:
/**
* 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) {
方法1:迭代法,时间复杂度O(n),空间复杂度O(1)
ListNode *pre=nullptr;
ListNode *cur=head;
while(cur!=nullptr){
ListNode *next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
方法2:头插法,时间复杂度O(n),空间复杂度O(1)
if(head==nullptr){
return head;
}
ListNode *pre=head;
ListNode *cur=head;
while(cur->next!=nullptr){
ListNode *next=cur->next;
cur->next=next->next;
next->next=pre;
pre=next;
}
return pre;
// //方法3:递归法
// if(!head||!head->next){
// return head;
// }
// ListNode *newHead=reverseList(head->next);
// head->next->next=head;
// head->next=nullptr;
// return newHead;
}
};
感觉:方法一好理解,方法二是我上数据结构课上老师讲的比较标准通用的解法,方法三……相比起来比较难理解,可以画个图。