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.
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function assert(m >= 1 && n >= 1 && m <= n); if(head == NULL) return head ; ListNode * headm, *p, *q,*preP,*endm; //find the mth node int i = 1; p = head ; preP = NULL; while(i<m &&p){ preP = p; p= p->next; i++; } //reverse Between m and n headm = NULL; endm = p; while(i<=n && p) { q = p; p = p->next; q->next = headm; headm = q; i++; } if(preP == NULL) head = headm; else preP->next = headm ; if(endm) endm->next = p; return head; } };