题解 | #链表内指定区间反转#

链表内指定区间反转

http://www.nowcoder.com/practice/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
        int cnt = 0;
        ListNode* dummyHead = new ListNode(-1);
        ListNode* p = dummyHead;
        p -> next = head;
        ListNode *pStart, *pEnd;
        while(p -> next!= NULL){
            if(cnt == m - 1) pStart = p;
            if(cnt == n) pEnd = p;
            p = p -> next;
            cnt ++;
        }
        if(cnt == n) pEnd = p; //n为结尾的时候注意特例

        ListNode* tail = pStart -> next;
        ListNode* nxtHead = pEnd -> next;
        pEnd -> next = NULL;
        reverseList(tail);
        pStart -> next = pEnd;
        tail -> next = nxtHead;
        return dummyHead -> next;
    }
    ListNode* reverseList(ListNode* head){
        ListNode* pre = NULL;
        while(head != NULL){
            ListNode* nxt = head -> next;
            head -> next = pre;
            pre = head;
            head = nxt;
        }
        return pre;
    }
};
全部评论

相关推荐

01-04 21:30
已编辑
河南工业大学 Java
27届学院本誓死冲击...:下次再发把个人信息隐藏掉,以防有心之人。相关课程删了,荣誉奖项只留蓝桥杯,把蓝桥杯写到教育经历里,按教育经历、实习经历、项目经历、专业技能这个顺序排版
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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