题解 | #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) {
         int count = 0;
         ListNode cur = head;
         while (cur != null) {
             count++;
            cur = cur.next;
         }
        
        if (count < k) {
            return head;
        }
        
        int term = count / k;
        
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode pre = preHead;
        ListNode tail;
        ListNode next;
        
        for (int i = 0; i < term; i++) {
            tail = pre.next;
            
            for (int j = 0; j < k - 1; j++) {
                next = tail.next;
                tail.next = next.next;
                next.next = pre.next;
                pre.next = next;
            }
            
            pre = tail;
        }
        
        return preHead.next;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
黑皮白袜臭脚体育生:看了这篇帖子之后已经第一百次质问老妈,仍然没有得到我的老妈是老板的回答
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务