zoukankan      html  css  js  c++  java
  • 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; }
  • 相关阅读:
    Android四大组件
    git命令记录
    .net core试水
    记一次NPOI的使用
    上位机开发经验教训总结
    Python爬虫,爬取腾讯漫画实战
    记一次微信小程序的开发
    sql使用cte表达式进行递归查询
    使用百度的webuploader进行附件上传
    Winform文件上传
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5400206.html
Copyright © 2011-2022 走看看