首页 > 其他 > 详细

LeetCode Reverse Linked List II

时间:2014-06-30 15:36:58      阅读:298      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!