Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n =
4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
處理這個問題還是挺復雜的,需要考慮很多邊界的測試用例。我總體的思路是先用循環標記m前一個節點和n後邊一個節點,把n後邊的節點首先作為當前逆轉節點的pre,然後循環n-m次完成所選節點部分的逆序,然後將標記的m節點前一個節點指向逆序後部分的頭節點即可。要考慮各種特殊情況,另外考慮即可。code如下:
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; inext;
}
for(int i=m;inext;
cur->next = pre;
pre = cur;
cur = temp;
}
if(m==1)
return pre;
head2->next = pre;
return head;
}
};