zoukankan      html  css  js  c++  java
  • #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  太久不写链表写的有点吃力啊 呜呜呜

  • 相关阅读:
    java中重载与重写的区别
    Java中数组的初始化方式
    break和continue的区别
    do while 循环和while循环的区别
    Java注释分类
    Java中的switch语句后面的控制表达式的数据类型
    DBA_TABLES之BLOCKS AND EMPTY_BLOCKS
    show_space 脚本
    Linux 6 配置multipath
    环保创业的可行之道——Leo鉴书上66
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10684832.html
Copyright © 2011-2022 走看看