LeetCode 25: Reverse Nodes in k-Group

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 25: Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。

/**
 * 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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 25. Reverse Nodes in k-Group ☆☆☆

Leetcode 25:Reverse Nodes in k-Group

LeetCode 25. Reverse Nodes in k-Group

leetcode25. Reverse Nodes in k-Group

leetcode 25 Reverse Nodes in k-Group

LeetCode 25: Reverse Nodes in k-Group