25. K 个一组翻转链表—new

232 阅读1分钟

image.png

思路

  • 先确定能翻转几组
  • 每组内进行m到n的反转链表
  • 对于反转m到n的问题,确定好循环次数,pre是不动的,循环内:
    • 先cur.next = ...
    • 再tmp.next = ...
    • 再pre.next = ...

09B407379DE77010A770DE8DEFB58D4F.png

代码

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        //计算链表长度
        int size = 0;
        ListNode node = head;
        while (node != null) {
            size++;
            node = node.next;
        }
        int round = size / k;//轮数,表示一共进行round次k个为一组的翻转
        //开始翻转
        ListNode pre = dummy;
        ListNode cur = dummy.next;
        for (int i = 0; i < round; i++) {
            for (int j = 1; j < k; j++) {//以k为大小的区间内相邻节点挨个翻转,类似翻转m到n
                ListNode tmp = cur.next;
                cur.next = tmp.next;
                tmp.next = pre.next;
                pre.next = tmp;
            }
            //一组的翻转结束,往后挪
            pre = cur;
            cur = pre.next;
        }
        return dummy.next;
    }
}
  • 如果剩下的凑不整的也要反转,加上这

C0B7F24D81D14B1E2AFFE3C87CE81B7E.png

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        //计算链表长度
        int size = 0;
        ListNode node = head;
        while (node != null) {
            size++;
            node = node.next;
        }
        int round = size / k;//轮数,表示一共进行round次k个为一组的翻转
        //开始翻转
        ListNode pre = dummy;
        ListNode cur = dummy.next;
        for (int i = 0; i < round; i++) {
            for (int j = 1; j < k; j++) {//以k为大小的区间内相邻节点挨个翻转,类似翻转m到n
                ListNode tmp = cur.next;
                cur.next = tmp.next;
                tmp.next = pre.next;
                pre.next = tmp;
            }
            //一组的翻转结束,往后挪
            pre = cur;
            cur = pre.next;
        }
        
        //如果剩下的凑不整的也要反转,加上这段
        if (cur != null) {
            while (cur.next != null) {
                ListNode tmp = cur.next;
                cur.next = tmp.next;
                tmp.next = pre.next;
                pre.next = tmp;
            }
        }
        
        return dummy.next;
    }
}