zoukankan      html  css  js  c++  java
  • LeetCode 25. 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.

    You may not alter the values in the nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For 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

    Subscribe to see which companies asked this question.

    • 可以申请一个vector数组, 将链表的值全部储存到vector中.
    • 每k个分为一组。
    • 对于每一组可以从头到位给链表赋值就行了。
    class Solution
    {
    public:
        ListNode* reverseKGroup(ListNode* head, int k)
        {
            vector<int> vec;
            ListNode *root = head;
            while(head != nullptr)
            {
                vec.push_back(head->val);
                head = head->next;
            }
            head = root;
            int res = 0;
            while(head != nullptr)
            {
                int b = res * k, e = (res+1)*k-1;
                if(e > vec.size() - 1)
                    break;
                while(b <= e)
                {
                    head->val = vec[e --];
                    head = head->next;
                }
                res ++;
            }
            return root;
        }
    };
    
  • 相关阅读:
    Java8 Optional使用方式
    ABAC框架-casbin
    Java数据脱敏(手机号|邮箱号|身份证号|银行卡号)
    使用OpenOffice将office文件转为pdf
    在线审批流设计
    Java 将带逗号的字符串转为List
    Java8 lambda常用操作
    Markdown合并单元格
    本博客已搬迁至rcst.xyz
    涂色(题解)
  • 原文地址:https://www.cnblogs.com/aiterator/p/6560171.html
Copyright © 2011-2022 走看看