zoukankan      html  css  js  c++  java
  • Reverse Nodes in k-Group

    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.

    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

    思路:

      很简单的翻转链表而已,把图画明白了就可以了。

    我的代码:

    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            int n = 0;
            while(head != null)
            {
                head = head.next;
                n++;
            }
            if(n < k) return dummy.next;
            ListNode pre = dummy;
            ListNode curpre = dummy.next;
            ListNode cur = curpre.next;
            for(int i = 0; i < n/k; i++)
            {
                for(int cnt = 1; cnt < k; cnt++)
                {
                    ListNode next = cur.next;
                    curpre.next = cur.next;
                    cur.next = pre.next;
                    pre.next = cur;
                    cur = next;
                }
                pre = curpre;
                curpre = curpre.next;
                if(curpre != null)
                    cur = curpre.next;
            }
            return dummy.next;
        }
    }
    View Code
  • 相关阅读:
    超链接
    Image中的alt
    预格式
    json字符串转json对象,json对象转换成java对象
    google-gson 解析json
    java HTTP请求工具
    JS文件中获取contextPath的方法
    eclipse中安装freemarker插件及ftl使用freemarker编辑器
    MyBatis 传入参数之parameterType
    typeAliases别名
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4350755.html
Copyright © 2011-2022 走看看