class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { if (head == NULL || n <= m) return head; int offset = n - m; ListNode* cur = head; ListNode* pre = NULL; while (cur != NULL && --m > 0) { pre = cur; cur = cur->next; } ListNode* start = cur; while (cur != NULL && offset-- > 0) { cur = cur->next; } ListNode* end = cur; ListNode* end_next = end->next; end->next = NULL; ListNode* rhead = reverse(start); if (pre == NULL) { head = rhead; } else { pre->next = rhead; } start->next = end_next; return head; } ListNode* reverse(ListNode* head) { ListNode* cur = head; ListNode* pre = NULL; while (cur != NULL) { ListNode* t = cur->next; cur->next = pre; pre = cur; cur = t; } return pre; } };
链表指针还是要小心着点,写着写着把前面想的要注意的地方给漏了
第二轮:
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.
第一次做的时候应该不算是one-pass
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 // 10:55 10 class Solution { 11 public: 12 ListNode *reverseBetween(ListNode *head, int m, int n) { 13 if (head == NULL || head->next == NULL) { 14 return head; 15 } 16 ListNode fakeHead(0); 17 fakeHead.next = head; 18 19 int k = m; 20 ListNode* pre = NULL; 21 ListNode* cur = &fakeHead; 22 while (k--) { 23 pre = cur; 24 cur = cur->next; 25 } 26 ListNode* first_tail = pre; 27 ListNode* reversed_tail = cur; 28 29 pre = NULL; 30 k = n - m + 1; 31 while (k--) { 32 ListNode* tmp = cur->next; 33 cur->next = pre; 34 pre = cur; 35 cur = tmp; 36 } 37 ListNode* reversed_head = pre; 38 ListNode* second_head = cur; 39 40 first_tail->next = reversed_head; 41 reversed_tail->next = second_head; 42 return fakeHead.next; 43 } 44 };