题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (k == 1) {
            return head;
        }
        if (head == null || head.next == null) {
            return head;
        }
        int times = 0;
        ListNode temp;
        ListNode op = new ListNode(-1), tmp;

        op.next = head;
        tmp = op;
        while (head.next != null) {
            temp = head.next;
            head.next = temp.next;
            temp.next = tmp.next;
            tmp.next = temp;
            times++;
            if (times % (k - 1) == 0) {
                tmp = head;
                if(tmp.next!=null){
                    head=tmp.next;
                }
                else{
                    return op.next;
                }
            }

        }
        
        if (times % (k - 1) != 0) {
            head=tmp.next;
            while (head.next != null) {
                temp = head.next;
                head.next = temp.next;
                temp.next = tmp.next;
                tmp.next = temp;
            }

        }

        return op.next;
    }
}

1、对于我来说,难点不在于如何反转,而在于一些临界值的处理,对可能出现null地方需要考虑增加临界值的处理。

2、核心部分在于循环不变式的构建,

类似于头插法,不变的是:头head,指向该次反转的tmp,因为要改变head的next、tmp的next,因此需要一个临时变量存储head的next。每次循环都是源于这三个“不变”变量的更改。

3、k值反转,实际上反转k-1次。

全部评论

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务