码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Reverse Linked List II

时间:2014-06-30 15:36:26      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   art   leetcode   io   

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

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

LeetCode Reverse Linked List II,布布扣,bubuko.com

LeetCode Reverse Linked List II

标签:style   blog   color   art   leetcode   io   

原文地址:http://www.cnblogs.com/lailailai/p/3816255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!