首页 > 代码库 > LeetCode Reverse Linked List II

LeetCode Reverse Linked List II

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;    }};

 链表指针还是要小心着点,写着写着把前面想的要注意的地方给漏了