题目:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,
return1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
看别人的答案然后做的,已经吐血了。。。周围太吵了,静不下心写代码。。
/**
* 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 || m == n)
return head;
ListNode dummy(-1);
dummy.next = head;
ListNode* firstTail = &dummy;
for (int i = 0; i < m-1; i++)
firstTail = firstTail->next;
ListNode* secondTail = firstTail->next;
ListNode* tmpHead = NULL;
ListNode* tmpNext = NULL;
ListNode* pTmp = firstTail->next;
int k = n - m + 1;
while (k-- > 0)
{
tmpHead = pTmp;
pTmp = pTmp->next;
tmpHead->next = tmpNext;
tmpNext = tmpHead;
}
firstTail->next = tmpHead;
secondTail->next = pTmp;
return dummy.next;
}
};