Reverse a linked list from positionm 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:
Givenm,
n satisfy the following condition:
1 ≤m ≤
n ≤ length of list.
这道题是反转链表中从m到n之间的节点,题目难度为Medium。
这道题和第206题相关,这样的题目相对比较简单,不过处理时比较繁琐,要注意考虑各种极限情况。具体代码:
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(!head) return head;
ListNode *cur = head, *pre = NULL;
ListNode *mLeft = NULL, *mPosi = NULL;
int cnt = 1;
while(cnt < m) {
pre = cur;
cur = cur->next;
cnt++;
}
mLeft = pre;
mPosi = cur;
while(cnt <= n) {
ListNode* tmp = cur;
cur = cur->next;
tmp->next = pre;
pre = tmp;
cnt++;
}
if(mLeft) mLeft->next = pre;
else head = pre;
mPosi->next = cur;
return head;
}
};
这里用mLeft表示第m个节点的前一个节点,用mPosi表示第m个节点,因为在反转链表指定部分之后需要修改相应的指针,因而这里用他们缓存这两个节点。