zoukankan      html  css  js  c++  java
  • LeetCode-25. 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.
    public ListNode reverseKGroup(ListNode head, int k) {//链表 my
            ListNode nhead = new ListNode(0);
            nhead.next=head;
            ListNode nodek = nhead;
            while(null!=nodek&&null!=nodek.next){
                ListNode nextnodek=nodek.next;//这k个结点的原始第一点,也是转换后的最后一个点
                ListNode cur=nodek.next;
                ListNode pre =null;
                ListNode beh=cur;
                int num =0;
           //判断是否还有k个点 while(null!=beh&&num<k){ beh=beh.next; num++; } if(num<k){ break; } num=0;
           //移动后面的k个点 while(null!=cur&&num<k){ beh=cur.next; cur.next= pre; pre= cur; cur = beh; num++; } nodek.next=pre; nodek=nextnodek; nodek.next=cur; } return nhead.next; }

    可读性更高一点的写法

    public ListNode reverseKGroup(ListNode head, int k) {//mytip
            ListNode nhead = new ListNode(0);
            nhead.next=head;
            ListNode nodek = nhead;
            ListNode cur = head;
            int num =0;
            while(null!=cur){
                num++;
                cur=cur.next;
            }
            cur=head;
            while(num>=k){
                ListNode nextnodek=nodek.next;
                ListNode pre =null;
                for (int i = 0; i < k; i++) {
                    head=head.next;
                    cur.next=pre;
                    pre =cur;
                    cur=head;
                }
                nodek.next=pre;
                nodek=nextnodek;
                nodek.next=cur;
                num-=k;
            }
            return nhead.next;
        }
    

    相关题  

    链表反转 LeetCode206 https://www.cnblogs.com/zhacai/p/10429295.html

    两两交换链表中的节点LeetCode24 https://www.cnblogs.com/zhacai/p/10559271.html

  • 相关阅读:
    技术收集
    Entity Framework的扩展库
    暂时收集
    php 处理高并发的思路
    nginx缓存优先级(缓存问题者必看)
    mysql5.5主从配置
    php源码编译常见错误解决方案
    今天开始要改变模式了
    nrpe 在ubuntu上安装遇到的问题
    zendstudio 10下载汉化
  • 原文地址:https://www.cnblogs.com/zhacai/p/10563446.html
Copyright © 2011-2022 走看看