题解 | #链表中的节点每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) {
        // 思路:每遍历取出 k 个节点(pre, k个 , curr ),将 k 截断翻转
        ListNode vNode = new ListNode(-1);
        vNode.next = head;

        ListNode pre = vNode;
        ListNode post = pre.next;
        ListNode start;
        ListNode curr;
        int i = 1;
        while (post != null) {
            if (i == k) {
                // 截断待翻转 k 个节点
                start = pre.next;
                pre.next = null;
                curr = post.next;
                post.next = null;
                // 翻转
                reverse(start, post);
                // 拼接并重置 pre,start
                pre.next = post;
                pre = start;
                start.next = curr;
                start = curr;
                // 剩余节点不足 k 组
                if (start == null) {
                    return vNode.next;
                } else {
                    post = start.next;
                    i = 2;
                }
            }
            if (post != null) {
                post = post.next;
                i++;
            } else {
                break;
            }
        }
        return vNode.next;
    }

    public static void reverse(ListNode start, ListNode end) {
        ListNode post = start.next;
        ListNode tmp;
        while (post != null) {
            tmp = post.next;
            post.next = start;
            start = post;
            post = tmp;
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务