『链表模板题』题解 | #链表内指定区间反转#

链表内指定区间反转

http://www.nowcoder.com/questionTerminal/b58434e200a648c589ca2063f1faf58c

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        // write code here
        if( m<1 || n<1 || m>n )
        {
            throw "errorInput";
        }

        if( nullptr==head || nullptr==head->next )
        {
            return head;
        }
        ListNode * dummy=new ListNode( 0x3f3f3f );
        dummy->next=head;

        //表示已经到了第1个节点
        ListNode * pre=dummy;
        ListNode * cur=head;
        int beginLoop=m-1;
        int endLoop=n;
        while( beginLoop-- )
        {
            cur=cur->next;
            pre=pre->next;
            --endLoop;
        }

        ListNode * sentry=nullptr;
        while( endLoop-- )
        {
            ListNode * temp=cur->next;
            cur->next=sentry;
            sentry=cur;
            cur=temp;
        }
        pre->next->next=cur;
        pre->next=sentry;

        ListNode * del=dummy;
        dummy=dummy->next;
        delete del;
        return dummy;
    }
};
全部评论

相关推荐

真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
有担当的灰太狼又在摸鱼:零帧起手查看图片
点赞 评论 收藏
分享
我:“加班需要有加班工资。”&nbsp;hr:“为什么?”&nbsp;哈哈哈哈哈哈哈离大谱
juntenor:你确实太理想化了,对社会不了解呀。这个和HR没有关系,这是国内特色,不然怎么还会有外包就这种逆天的存在呢。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务