• #Leetcode# 25. Reverse Nodes in k-Group


    https://leetcode.com/problems/reverse-nodes-in-k-group/

    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.

    Example:

    Given this linked list: 1->2->3->4->5

    For k = 2, you should return: 2->1->4->3->5

    For k = 3, you should return: 3->2->1->4->5

    Note:

    • Only constant extra memory is allowed.
    • You may not alter the values in the list's nodes, only nodes itself may be changed.

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(!head) return NULL;
            int cnt = 0;
            ListNode *cur = new ListNode(-1);
            ListNode *dummy = cur;
            vector<int> a, b;
            ListNode *pre = head;
            while(pre) {
                a.push_back(pre -> val);
                pre = pre -> next;
            }
            cnt = a.size();
            if(k > cnt) return head;
            //k %= cnt;
            if(!k) return reverseList(head);
            int rec = cnt / k;
            for(int i = 0; i < rec * k; i += k) {
                for(int j = i + k - 1; j >= i; j --) {
                    b.push_back(a[j]);
                }
            }
            if(rec * k != cnt)
                for(int i = rec * k; i < cnt; i ++)
                    b.push_back(a[i]);
            for(int i = 0; i < b.size(); i ++) {
                ListNode *t = new ListNode(b[i]);
                t -> next = NULL;
                dummy -> next = t;
                dummy = dummy -> next;
            }
            return cur -> next;
        }
        ListNode* reverseList(ListNode* head) {
            ListNode *revhead = NULL;
            ListNode *pnode = head;
            ListNode *pre = NULL;
            
            while(pnode) {
                if(!pnode -> next)
                    revhead = pnode;
                
                ListNode *nxt = pnode -> next;
                pnode -> next = pre;
                pre = pnode;
                pnode = nxt;
            }
            return revhead;
        }
    };
    

      就是很简单的每 k 个反转一下 但是和之前做过的类似题目不一样的是 k 就是 k 不要 k%= cnt 会 WA  太久不写链表写的有点吃力啊 呜呜呜

  • 相关阅读:
    Moinmoin wiki 中文附件名的解决办法
    TFS2012 服务器安装
    利用openssl自建CA体系
    latex 添加Bibtex 全解(使用TeXstudio)
    BlockStack常见词语
    量子计算和量子信息: 读书笔记
    Vue 中的keep-alive 什么用处?
    打包vue文件,上传到服务器
    修改vscode的文件,对应的磁盘文件不改变
    html5的 history模式和hash模式
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10684832.html
Copyright © 2020-2023  润新知