题解 | #BM3 链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        if(head == null || head.next == null || k<=1){
            return head;
        }
        //虚拟头节点
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        
        //循环中会用到的pre next head(相当于BM2的cur)
        ListNode pre = dummyHead;
        ListNode next = null;
        
        int n = length(head);//可以这样用
        int m = 0;
        for(int i = 0; i < n-(n%k); i++){
            if(m < k-1){ //k个元素只需要跑k-1次即可,第k的时候用来重置pre head
                next = head.next;
                head.next = next.next;
                next.next = pre.next;
                pre.next = next;
                m++;
            }else{
                m = 0;
                pre = head;
                head = head.next;
            }
        }
        return dummyHead.next;
        
    }
    
    public int length(ListNode now){    //获取链表长度
        int cnt = 0;
        if(now != null) cnt = 1;
        while(now.next != null){
            cnt ++; 
            now = now.next;
        }
        return cnt;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务