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

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

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

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null || head.next == null || k == 1) return head;
        ListNode front = new ListNode(-1);
        ListNode cur = head;
        front.next = head;
        ListNode l = null;
        ListNode prel = front;
        ListNode next = null;
        boolean reverse = false;
        while (head != null) {
            int q = k;
            while (head != null && q-- > 0) {
                head = head.next;
            }
            if (q == -1 || q == 0) {
                reverse = true;
                ListNode pre = cur;
                l = pre;
                cur = cur.next;

                for (int i = 1; i < k; i++) {
                    next = cur.next;
                    cur.next = pre;
                    pre = cur;
                    cur = next;
                }
                prel.next = pre;
                prel = l;
            }
            if (q >= 0) {
                if (reverse)
                    l.next = next;
            }
        }
        return front.next;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 11:31
点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 10:39
一个证都没&nbsp;我能填什么
程序员小白条:别人有,你为什么没有,还是这个道理,社会就是比较,竞争,淘汰,你要安逸,那么就要做好淘汰的准备
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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