• 25. Reverse Nodes in k-Group


        /*
         * 25. Reverse Nodes in k-Group 
         * 2016-4-16 by Mingyang
         * 这道题目刚开始想的时候就觉得很难,这道题目难就难在必须构造一种特殊的reverse方法
         * 这样才能够让整个代码简单
         * 那么如何表达一段需要reverse的list呢?我们用一个i不断的累加,当模k等于0的时候
         * 就是我们所说的一段需要reverse的node
         */
        public static ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || k == 1)
                return head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode pre = dummy;
            int i = 0;
            while (head != null) {
                i++;
                if (i % k == 0) {//并且准确的限定了我们需要的范围
                    pre = reverse(pre, head.next);
    //return的是reversed list的最后一个,我们设为pre,这样就可以重新开始了 head = pre.next; } else { head = head.next; } } return dummy.next; } /** * Reverse a link list between pre and next exclusively * an example: * a linked list: * 0->1->2->3->4->5->6 * | | * pre next * after call pre = reverse(pre, next) * * 0->3->2->1->4->5->6 * | | * pre next * @param pre * @param next * @return the reversed list's last node, which is the precedence of parameter next */ /* * 在下面的代码中有意思的是while里面的部分,一个顺序都不能错 * reverse list可以最简单的方法就是直接头就是尾,尾就是头--链表反转 * 这里不是用的这种方法,这里用的是遍历,反转,这里就要注重顺序啦 * pre-x-x-last-cur-x * 首先是last指向cur后面的x * cur指向第一个,然后pre指向cur。 * 最后再把cur放到last的后面,相当于cur到了下一个数 */ private static ListNode reverse(ListNode pre, ListNode next){ ListNode last = pre.next;//where first will be doomed "last" ListNode cur = last.next; while(cur != next){ last.next = cur.next; cur.next = pre.next; pre.next = cur; cur = last.next; } return last; }
  • 相关阅读:
    深入探析c# Socket
    异步上传文件并获得返回值(完全跨域)
    ASP.NET MVC的Model元数据与Model模板:模板的获取与执行策略
    数值压缩存储方法Varint
    JavaIO知识总结2
    ASP.NET MVC URL重写与优化
    检测是否为HTML5新标签
    Context+ContextScope——这是否可以看作一种设计模式?
    体验vs11 Beta
    选择实现—简单工厂
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5400206.html
Copyright © 2020-2023  润新知