Reverse a linked list from position m to n.
Notice
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Example
Given 1->2->3->4->5->NULL
, m = 2
and n = 4
, return1->4->3->2->5->NULL
.
要注意是否从第一个节点开始翻转,1)是则保存第n+1个节点,进行翻转,然后返回s2)否则保存第m-1个节点,和第n+1个节点,翻转
/** * 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 int i = m; int j = n - m; ListNode *p = head; int count = 0; while(p != NULL) { p = p->next; count++; } if(count < n)return NULL; p = head; while(i > 2) { p = p->next; i--; } ListNode *bf = p; if(m != 1)p = p->next; ListNode *q = p; while(j >= 0) { q = q->next; j--; } ListNode *s = q; while(p != q) { ListNode *tmp = p->next; p->next = s; s = p; p = tmp; } if(m != 1) { bf->next = s; return head; } else return s; } };