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.
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode *dumllHead = new ListNode(-1);
dumllHead -> next = head;
ListNode *p = dumllHead;
ListNode *pfore = dumllHead;
ListNode *pre = dumllHead;
ListNode *q = dumllHead;
ListNode *qback = q -> next;
int cnt = 0,mm = m,nn = n;
while(nn){
if(mm){
pfore = p;
p = p -> next;
mm --;
}
pre = q;
q = qback;
nn --;
cnt ++;
if(cnt > m){
qback = q -> next;
q -> next = pre;
}else
qback = q -> next;
}
pfore -> next = q;
p -> next = qback;
return dumllHead -> next;
}
};
本文介绍了一种算法,用于在单次遍历中就地反转链表的指定区间,从位置m到n。提供了完整的C++实现示例,并讨论了边界条件。
554

被折叠的 条评论
为什么被折叠?



