【牛客刷题】反转固定区间链表、每k个节点一组反转

 链表内指定区间反转_牛客题霸_牛客网

【牛客刷题】反转固定区间链表、每k个节点一组反转_第1张图片 

    ListNode* reverseList(ListNode* head, ListNode* tail) {
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while (cur != tail) { 最后cur就是tail
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
    
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* dummyNode = new ListNode(0);
        dummyNode->next = head;
        ListNode* pre = dummyNode;
        for (int i = 1; i < m; i++) {
            pre = pre->next;
        }
        ListNode* start = pre->next;
        ListNode* end = pre->next;
        for (int i = m; i <= n; i++) {
            end = end->next;
        }
        
        pre->next = reverseList(start, end);//执行这个函数以后start变成传过去的链表的尾节点,所以直接连接start和end就行
        start->next = end;
        return dummyNode->next;
    }

链表中的节点每k个一组翻转_牛客题霸_牛客网 

【牛客刷题】反转固定区间链表、每k个节点一组反转_第2张图片

    ListNode* reverseList(ListNode* head, ListNode* tail) {
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while (cur != tail) {
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        if (k == 1 || head->next == nullptr || head == nullptr) return head;

        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* start = pre->next;
        ListNode* end = pre;
        while (end->next != nullptr && end != nullptr) {
            start = pre->next;
            end = pre;
            int i;
            for (i = 0; i <= k; i++) {
                if (end->next) end = end->next;
                else {
                    end = nullptr;
                    break;
                }
            }
            if (i < k) break;
            else {
                pre->next = reverseList(start, end);
                start->next = end;
                pre = start;
            }
        }
        return dummy->next;
    }

你可能感兴趣的:(链表,java,数据结构)