题解 | #反转链表#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
这个方法简直太妙了,记录以下
假设: pre->cur->cur_next->pp
核心代码即:
cur_next=cur->next; //记录求next
cur->next=cur->next->next; //翻转cur和cur_next
cur_next->next=pre->next;
pre->next=cur_next;
/**
* 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) {
// write code here
ListNode* dummyNode = new ListNode(-1);
dummyNode->next =head;
ListNode* pre = dummyNode;
for(int i=0;i<m-1;i++){ //pre指向了第m-1个结点
pre = pre->next;
}
ListNode* cur = pre->next; //开始翻转
ListNode* Cur_next=nullptr ;
for(int i=0;i<n-m;i++){
Cur_next = cur->next;
cur->next = Cur_next->next;
Cur_next->next = pre->next;
pre->next = Cur_next ;
}
return dummyNode->next;
}
};