题目:从m到n进行链表旋转
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.
Subscribe to see which companies asked this question
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head == NULL) return NULL;
if(n < m || m < 1 || n < 1) return head;
ListNode* tmpN = head;
ListNode* tmpNH = NULL;
ListNode* tmpV = NULL;
ListNode* tmpE = NULL;
bool flag = true;
bool flag1 =true;
int numNode = 0;
while(tmpN != NULL)
{
++numNode;
if(numNode >= m && numNode <= n)
{
flag = false;
ListNode* tmpL = tmpN;
if(flag1)
{
tmpE = tmpN;
flag1 = false;
}
tmpN = tmpN->next;
tmpL->next = tmpV;
tmpV = tmpL;
}else
{
if(flag)
{
tmpNH = tmpN;
}else
{
break;
}
tmpN = tmpN->next;
}
}
if(tmpNH)
tmpNH->next = tmpV;
else
head = tmpV;
if(tmpE) tmpE->next = tmpN;
return head;
}
};