码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 25: Reverse Nodes in k-Group

时间:2017-09-04 15:59:12      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:val   logs   anr   tco   boolean   solution   group   bool   res   

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode result = new ListNode(0);
        ListNode tail = result;
        int count = k;
        while (head != null) {
            count = k;
            ListNode runner = head;
            if (!canReverse(runner, k)) {
                break;
            }
            
            while(count-- > 0) {
                runner = head;
                head = head.next;
                runner.next = tail.next;
                tail.next = runner;
            }
            
            while (tail.next != null) {
                tail = tail.next;
            }
        }
        
        if (head != null) {
            tail.next = head;
        }
        return result.next;
    }
    
    private boolean canReverse(ListNode head, int num) {
        while (num-- > 0) {
            if (head == null) {
                return false;
            }
            head = head.next;
        }
        return true;
    }
}

 

LeetCode 25: Reverse Nodes in k-Group

标签:val   logs   anr   tco   boolean   solution   group   bool   res   

原文地址:http://www.cnblogs.com/shuashuashua/p/7473822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!