题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
大神好多,学到了遍历一次的算法
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode *vhead=new ListNode(0);
vhead->next=head;
vhead->val=0;
ListNode *cur=vhead;
for(int i=1;i<=m-1;i++)
cur=cur->next;
ListNode *pre=cur;
cur=cur->next;
ListNode *cur_next=cur->next;
for(int i=m;i<n;i++){
cur->next=cur_next->next;
cur_next->next=pre->next;
pre->next=cur_next;
cur_next=cur->next;
}
if(m==1)
return pre->next;
return vhead->next;
}
};
}