LeetCode-K 个一组翻转链表

213 阅读1分钟

算法记录

LeetCode 题目:

  给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。


说明

一、题目

  k 是一个正整数,它的值小于或等于链表的长度。

  如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

二、分析

  • 和翻转给定区间的链表方法差不多,只需要依次遍历整条链表上的 K 个节点,然后将这段区间内的链表进行反转返回。
  • 直至链表结束或者剩余节点数已经不满足需要反转的数量为止。
class Solution {
    public ListNode reverse(ListNode head, ListNode tail) {
        while(head != tail) {
            ListNode temp = head;
            head = head.next;
            temp.next = tail.next;
            tail.next = temp;
        }
        return head;
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode hair = new ListNode(-1, head);
        ListNode mi = hair;
        ListNode pre = head, tail = null;
        while(pre != null) {
            tail = pre;
            for(int i = 0; i < k - 1; i++) {
                tail = tail.next;
                if(tail == null) return hair.next;
            }
            pre = reverse(pre, tail);
            mi.next = pre;
            for(int i = 0; i < k; i++) {
                pre = pre.next;
                mi = mi.next;
            }  
        }
        return hair.next;
    }
}

总结

熟悉链表的反转。