题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
方法一:用快慢指针,快指针先走n-m步,再快慢指针一起走,获得要反转期间的首尾位置,在利用反转链表的知识,将反转后的链表与前面部分和后面部分的剩余结点相连。 /** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ ListNode* reverseBetween(ListNode* head, int m, int n) { if(head==NULL||head->next==NULL) { return head; } ListNode* slow=head; ListNode* quick=head; ListNode*new_point=new ListNode(0); new_point->next=head; ListNode* p0=new_point; int num=n-m; while(num!=0) { quick=quick->next; num--; } num=1; while(num!=m) { p0=slow; slow=slow->next; quick=quick->next; num++; } ListNode* pre=NULL; ListNode* temp=NULL; ListNode* temp1=quick->next; while(slow!=temp1) { temp=slow->next; slow->next=pre; pre=slow; slow=temp; } p0->next->next=slow; p0->next=pre; return new_point->next; } }; 方法二:用前后指针,以及一个temp指针保存cur的下一个结点的位置,在利用结点之间的关系 /** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ ListNode* reverseBetween(ListNode* head, int m, int n) { if(head==NULL||head->next==NULL) { return head; } ListNode*new_point=new ListNode(0); new_point->next=head; ListNode*pre=new_point; ListNode*cur=head; for(int i=1;i<m;i++) { pre=cur; cur=cur->next; } ListNode*temp=NULL; for(int i=m;i<n;i++) { temp=cur->next; cur->next=temp->next; temp->next=pre->next; pre->next=temp; } return new_point->next; } };