[LeetCode] Reverse Linked List II
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.
画图会比较容易理解
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *reverseBetween(ListNode *head, int m, int n) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 if (head == NULL) 15 return NULL; 16 17 ListNode *q = NULL; 18 ListNode *p = head; 19 for(int i = 0; i < m - 1; i++) 20 { 21 q = p; 22 p = p->next; 23 } 24 25 ListNode *end = p; 26 ListNode *pPre = p; 27 p = p->next; 28 for(int i = m + 1; i <= n; i++) 29 { 30 ListNode *pNext = p->next; 31 32 p->next = pPre; 33 pPre = p; 34 p = pNext; 35 } 36 37 end->next = p; 38 if (q) 39 q->next = pPre; 40 else 41 head = pPre; 42 43 return head; 44 } 45 };