题目
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.
反转链表中第m至第n个元素
代码
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL || head->next == NULL || m == n) return head;
ListNode* h = new ListNode(0);///新的头
h->next = head;
ListNode *p = head, *pre = h;///开始反转的节点及前一个节点
for(int i=1; i<m; i++){
p = p->next;
pre = pre->next;
}
ListNode *q = p->next, *tail = p, *t;
int time = n - m;
while (q != NULL) {
if(time <= 0)
break;
t = q->next;
q->next = p;
p = q;
q = t;
--time;
}
pre->next = p;
tail->next = q;
return h->next;
}
};