玩命加载中 . . .

25-k个为一组反转链表


LeetCode 25. Reverse Nodes in k-Group

LeetCode-25

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

method 1: 迭代

局部反转:反转[first, last),就是把pre设置为last,条件改成first != last,逻辑与全局反转类似

ListNode* reverse(ListNode *first, ListNode *last) {
    ListNode *pre = last;
    while (first != last) {
        ListNode *tmp = first->next;
        first->next = pre;
        pre = first;
        first = tmp;
    }
    return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
    ListNode *dummy = new ListNode(0, head);
    head = dummy;
    while (head->next) {    // len是k的倍数的话,head会指向最后一个元素,就退出
        ListNode *node = head->next;    // 先记录head的下一个节点,node会成为下一个反转节点的前一个节点
        ListNode *cur = head->next;
        for (int i = 0; i < k; i++) {       // cur移动k步
            if (!cur) return dummy->next;   // 不够k个直接返回
            cur = cur->next;
        }
        head->next = reverse(head->next, cur);  // 反转[head->next,cur)
        head = node;    // 做连接,head指向cur前面的节点
    }
    return dummy->next;
}

时间复杂度:$O(n)$,head指针会在$\mathcal{O}(\lfloor \frac{n}{k} \rfloor)$个节点上停留,每次停留需要进行一次$\mathcal{O}(k)$的翻转操作
空间复杂度:$O(1)$

method 2: 递归

每次反转完一段,node是这一段新的头结点,要返回的是node
做连接:head反转完是这一段的尾节点,要指向下一段的头结点,也就是递归的返回值

// 局部反转
ListNode *reverse(ListNode *head, ListNode *tail) {
    ListNode *pre = tail;
    while (head != tail) {
        ListNode *tmp = head->next;
        head->next = pre;
        pre = head;
        head = tmp;
    }
    return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
    ListNode *cur = head;
    for (int i = 0; i < k; i++) {
        if (!cur) return head;  // 不够k个
        cur = cur->next;
    }
    ListNode *node = reverse(head, cur);        // 反转[head,cur)
    head->next = reverseKGroup(head->next, k);  // 做连接,再处理下一段
    return node;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录