解答:
/*** 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;}
};
感覺:方法一好理解,方法二是我上數據結構課上老師講的比較標準通用的解法,方法三……相比起來比較難理解,可以畫個圖。