题目
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.
思路
之前整理过关于链表翻转的题目,这个题是在那个基础上要求实现固定位置之间的翻转。思路同之前,指针走到这里进行翻转就可以了。我的思路和Hot解法思路是一致的。
但要注意,用new运算符动态申请内存时,使用后一定要记得delete,否则面试官会非常不满意。
代码
ListNode* reverseBetween(ListNode* head, int m, int n) {
int cnt = n-m+1;
ListNode* prehead = new ListNode(-1);
prehead->next = head;
ListNode* tmp=prehead;
while(--m){
tmp = tmp->next;
}
ListNode* nhead=tmp;
tmp=tmp->next;
ListNode* prev=tmp;
ListNode* next=tmp->next;
ListNode* ntail=tmp;
while(cnt--){
next=tmp->next;
tmp->next=prev;
prev=tmp;
tmp=next;
}
ntail->next=next;
nhead->next=prev;
head = prehead->next;
delete prehead;
prehead=NULL;
return head;
}