题解 | #链表中的节点每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
        ListNode pre = null;
        ListNode cur = null;
        ListNode next = null;
        ListNode tmp = head;
        int index = 0;
        ListNode head1 = null;
        ListNode tail = null;
        boolean flag = false;
        while (tmp != null) {

            cur = tmp;
            next = tmp.next;

            if (index == 0) {
                head1 = tmp;
                flag = false;
            } else if (index == k - 1) {
                tail = tmp;
                reverseKGroup1(head1, tail);
                //链接外部
                if (pre != null) {
                    pre.next = tail;
                } else {
                    head = tail;
                }
                pre = head1;
                flag = true;
            }
            tmp = next;
            index = ++index % k;

        }
        if(!flag && pre != null){
            pre.next = head1;
        }
        return head;
    }

    public void reverseKGroup1(ListNode start, ListNode end) {
        ListNode s = start;
        ListNode e = end;
        ListNode pre = null;
        ListNode cur = null;
        ListNode next = null;
        while (s != e) {

            cur = s;
            next = s.next;
            cur.next = pre;

            pre = cur;
            s = next;
        }
        e.next = pre;
        System.out.println();
    }
}
  1. 循环链表节点
  2. 反转的时候用三个变量保存前一个节点,当前节点,后一个节点
  3. 处理k个循环
  4. 处理循环k个之后与外部的链接
  5. 处理最后不够k个节点
全部评论

相关推荐

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