jason89521 / leetcode_note

0 stars 0 forks source link

2074. Reverse Nodes in Even Length Groups #4

Open jason89521 opened 3 months ago

jason89521 commented 3 months ago

Practice Dates

Description

Link: https://leetcode.com/problems/reverse-nodes-in-even-length-groups/description/

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseEvenLengthGroups(ListNode* head) {
        int groupLen = 2;
        ListNode* tempHead = head;
        while (tempHead->next != nullptr) {
            ListNode* node = tempHead;
            int nodeCount = 0;
            for (int i = 0; i < groupLen; i++) {
                if (node->next == nullptr) {
                    break;
                }
                node = node->next;
                nodeCount += 1;
            }

            if (nodeCount % 2 != 0) {
                tempHead = node;
            } else {
                ListNode* nextHead = tempHead->next;
                ListNode* prev = node->next;
                ListNode* cur = tempHead->next;
                while(prev != node) {
                    ListNode* next = cur->next;
                    cur->next = prev;
                    prev = cur;
                    cur = next;
                }
                tempHead->next = node;
                tempHead = nextHead;
            }

            groupLen += 1;
        }

        return head;
    }
};

Performance

Time complexity: