题解 | #链表中的节点每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;
    }
}

全部评论

相关推荐

02-15 22:29
门头沟学院 Java
点赞 评论 收藏
分享
黑皮白袜臭脚体育生:春节刚过就开卷吗?哈基馆,你这家伙......
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务