25. K 个一组翻转链表

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

链表题,这个是基于翻转链表魔改而来,我们可以搭配翻转链表那题来食用。

题目要求k个一组,我们就是用一个计数器去技术,每当计数器到达k后,就把slow.next置为空,使得它单独成为一个链表,然后把这个链表放入到反转链表的题目的代码中就可以让他翻转了。

/**
 * 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) {
        int count = 0;
        ListNode dummy = new ListNode(-1);
        ListNode l = dummy;
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = null;
        while(fast != null){
            while(fast != null && count < k){
                count++;
                fast = fast.next;
            }
            if(count < k || fast == null){
                break;
            }
            slow = fast;
            fast = fast.next;
            slow.next = null;
            ListNode temp = l.next;
            l.next = helper(l.next);
            temp.next = fast;
            l = temp;
            count = 1;
        }
        return dummy.next;
    }

    private ListNode helper(ListNode head){
        ListNode pre = head;
        ListNode cur = head;
        ListNode behind = null;
        while(pre != null){
            pre = pre.next;
            cur.next = behind;
            behind = cur;
            cur = pre;
        }
        return behind;
    }
}

我的翻转链表代码使用的是遍历法,前中后三个指针交替交换他们的指向即可。

原文地址:https://www.cnblogs.com/ZJPaang/p/12899071.html