Reverse Linked List II
未完成,还可以找到更好的解
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 if (m == n) 13 return head; 14 15 ListNode *before = new ListNode(0); 16 before->next = head; 17 for (int i = 1; i < m; ++i) 18 before = before->next; 19 20 ListNode *cur = before->next; 21 ListNode *cur_fol = cur->next; 22 ListNode *behind = cur_fol; 23 24 for (int i = m; i < n; ++i) 25 behind = behind->next; 26 27 int num = n - m + 1; 28 while (num--) { 29 cur->next = behind; 30 behind = cur; 31 cur = cur_fol; 32 if (cur_fol) 33 cur_fol = cur_fol->next; 34 } 35 36 if (m == 1) 37 head = behind; 38 else 39 before->next = behind; 40 41 return head; 42 43 } 44 };