题目:
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.
cpp:
class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode *Head = new ListNode(-1); Head->next = head; ListNode *tail1 = Head; for(int i=1;i<m;i++){ tail1 = head; head = head->next; } ListNode *mNode = tail1->next; ListNode* cur = nullptr; for(int i=m;i<=n;i++){ cur = head; head = cur->next; cur->next = tail1->next; tail1->next= cur; } if(cur->next!= nullptr){ mNode->next = head; } return Head->next; } };