翻转链表中第m个节点到第n个节点的部分
注意事项
m,n满足1 ≤ m ≤ n ≤ 链表长度
下面是一个傻逼解法。。。
/**
* Definition of singly-linked-list:
*
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The head of linked list.
* @param m: The start position need to reverse.
* @param n: The end position need to reverse.
* @return: The new head of partial reversed linked list.
*/
ListNode *reverseBetween(ListNode *head, int m, int n) {
// write your code here
if (head == NULL) {
return NULL;
}
ListNode *mHead;
ListNode *mPreHead = NULL;
ListNode *nHead;
ListNode *nNextHead = NULL;
mHead = head;
nHead = head;
int i = 1;
while(i < n) {
if (i < m) {
if (i == m-1) {
mPreHead = mHead;
}
mHead = mHead->next;
}
nHead = nHead->next;
if(i == n-1) {
nNextHead = nHead->next;
}
i++;
}
if (mHead == nHead) {
} else if (mHead->next == nHead) {
/*ListNode *temp = nHead;
nHead = mHead;
mHead = temp;*/
if (mPreHead != NULL) {
mPreHead->next = nHead;
}
// if (nNextHead != NULL) {
mHead->next = nNextHead;
// }
nHead->next = mHead;
if (mPreHead == NULL) {
return nHead;
}
return head;
} else {
ListNode *pre = mHead;
ListNode *middle = mHead->next;
ListNode *behind = middle->next;
if (nNextHead != NULL) {
pre->next = nNextHead;
}
middle->next = pre;
pre = middle;
middle = behind;
behind = behind->next;
while(behind != nNextHead) {
middle->next = pre;
pre = middle;
middle = behind;
behind = behind->next;
if (behind == nNextHead) {
middle->next = pre;
if (mPreHead != NULL) {
mPreHead->next = middle;
}
if (m==1) {
return middle;
}
}
}
}
return head;
}
};