Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given1->2->3->4->5->NULL
, M = 2 and n = 4,
Return1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
It is still complicated to deal with this problem. Many boundary test cases need to be considered. My general idea is to mark the previous node of m and the node behind n cyclically, and use the node behind n as the pre of the current reverse node first, then, complete the reverse order of the selected node parts n-m times, and point the previous node of the marked m node to the header node of the backward part. Consider special cases. The code is as follows:
class Solution {public: ListNode *reverseBetween(ListNode *head, int m, int n) { if(head==NULL || m<0 || n<0) return head; if(head->next == NULL || m==n) return head; ListNode *head2=NULL,*pre,*cur,*temp=head; for(int i=0; i
next; } for(int i=m;i
next; cur->next = pre; pre = cur; cur = temp; } if(m==1) return pre; head2->next = pre; return head; }};