力扣25.K个一组翻转链表 | 链表 | 递归加迭代

分析:

迭代翻转每k个节点,然后递归迭代直到最后一层。

代码:
点击查看代码
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        //1.
        if(head == null || k == 1){
            return head;
        }
        //2.
        ListNode check = head;
        for(int i = 0; i < k;i++){
            if(check == null){
                return head;
            }
            check = check.next;
        }
        //3.
        ListNode pre = null;
        ListNode cur = head;
        ListNode temp = null;
        for(int i = 0 ; i < k ; i++){
            temp = cur.next;
            cur.next = pre;//反转一个指针
            pre = cur;
            cur = temp;
        }

        //4.
        head.next = reverseKGroup(cur , k);

        //5
        return pre;
    }
总结:

反转只需要改变当前节点指针向前一个节点,然后两个指针往后移就可以了,别再考虑为什么前一个节点不用动了,唯一需要记得就是反转前先记一下next节点。

posted @ 2025-08-31 21:23  柳成荫y  阅读(12)  评论(0)    收藏  举报