• 25. Reverse Nodes in k-Group


    description:

    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.
    Note:

    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
    

    my answer:

    感恩

    画图,没有难点,就是来回挪,一个循环找组,就是找到k个数看有没有,另一个函数在组内翻转,翻转的原理就是一个一个的把节点挪到第一个的位置上,其他的后挪。

    
    

    大佬的answer:

    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if (!head || k == 1) return head;//这里是返回原列表不是返回NULL
            ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = head;//这里cur = head,而不是cur = pre->next,因为此时pre的下一个是啥不知道,之后才会定义
            dummy->next = head;
            for (int i = 1; cur; ++i) {//这里是从1开始,条件是cur有意义,这里的i并没有传统意义上的计数,而是一个外部的技术,迭代的不是i,是cur
                if (i % k == 0) {
                    pre = reverseOneGroup(pre, cur->next);
                    cur = pre->next;
                } else {
                    cur = cur->next;
                }
            }
            return dummy->next;
        }
        ListNode* reverseOneGroup(ListNode* pre, ListNode* next) {
            ListNode *last = pre->next, *cur = last->next;
            while(cur != next) {
                last->next = cur->next;
                cur->next = pre->next;
                pre->next = cur;
                cur = last->next;
            }
            return last;
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    实体类实现序列化
    异常处理
    Springboot的模块化使用
    Springboot的开始
    RxJava用法
    okhttp的Post方式
    OKhttp使用
    soundPool声音池
    ScheduledExecutor定时器
    timer定时器
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10888583.html
Copyright © 2020-2023  润新知