zoukankan      html  css  js  c++  java
  • Leetcode: Reverse Nodes in k-Group

    仅允许使用常数时间, 交换 k-group 的节点

    思路:

    1. 完全逆转一个链表: 每遍历到一个节点, 就将该节点放在链表首位

    2. 在(1) 的基础上添加大小为 j 的窗口

    总结:

    1. 看来上一道题目思路也不是最优的

    代码: update

    class Solution {
    public:
        ListNode *reverseKGroup(ListNode *head, int k) {
            ListNode *newHead = new ListNode(0);
            newHead->next = head;
    
            int cnt = 0;
            ListNode *cur_node = head;
            ListNode *last_tail = newHead;
            while(cur_node) {
                cnt++;
                if(cnt == k) {
                    ListNode *cp = cur_node->next;
    
                    cur_node->next = NULL;
                    last_tail = reverseList(last_tail->next, last_tail);
                    last_tail->next = cp;
                    
                    cur_node = cp;
                    cnt = 0;
                    continue;
                }
                cur_node = cur_node->next;
            }
            return newHead->next;
        }
    
        ListNode *reverseList(ListNode*head, ListNode*last_tail) {
            ListNode *next_node = head->next;
            ListNode *res = head;
            while(next_node) {
                ListNode *tmp = next_node->next;
                next_node->next = head;
                head = next_node;
                next_node = tmp;
            }
            last_tail->next = head;
            return res;
        }
    };
  • 相关阅读:
    Java第一次作业
    第十一次作业
    第十次作业
    第九次作业
    第八次作业
    第七次作业
    第六次作业
    第五次作业
    java第三次实验
    java 第二次实验
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3459729.html
Copyright © 2011-2022 走看看