首页 > 其他 > 详细

Reverse Linked List II

时间:2016-02-27 23:32:37      阅读:322      评论:0      收藏:0      [点我收藏+]

题目:

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

 

cpp:

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode *Head = new ListNode(-1);
        Head->next = head;
        ListNode *tail1 = Head;
        for(int i=1;i<m;i++){
            tail1 = head;
            head = head->next;
        }
        ListNode *mNode = tail1->next;

        ListNode* cur = nullptr;
        for(int i=m;i<=n;i++){
            cur = head;
            head = cur->next;
            cur->next = tail1->next;
            tail1->next= cur;
        }

        if(cur->next!= nullptr){
            mNode->next = head;
        }

        return Head->next;
    }
};

 

Reverse Linked List II

原文:http://www.cnblogs.com/wxquare/p/5223823.html

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