92

it2022-05-05  107

一开始的代码  

想着遍历到链表的第m个结点

然后从m到n进行迭代 接着return 可是 代码出错了

class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(!head){ return nullptr; } ListNode*first=head; int temp; for(int i=1;i++;i<m){ first=first->next; temp=first->val; } ListNode*head1=first; ListNode*second=first->next; for(int p=1;p++;p<m-n){ while(second != nullptr){ first->next = second->next; ListNode* temp1 = second->next; second->next = head1; head1 = second; second = temp1; } return head; } } };

改进:

 

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (!head || !head->next) { return head; } ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* first = dummy; for (int i = 0; i < m - 1; i++) { first = first->next; } ListNode* start = first->next; ListNode* second = start->next; for (int i = 0; i < n - m; i++) { start->next = second->next; second->next = first->next; first->next = second; second = start->next; } return head; } };

时间复杂度为O(n)

空间复杂度为O(1)


最新回复(0)