题解 | 链表中的节点每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) {
        ListNode phead = new ListNode(-1);
        if (head == null || k == 1 || head.next == null) {
            return head;
        }
        phead.next = head;
        ListNode tail = phead;
        ListNode start = head;
        ListNode end = tail.next;
	  //首先找到需要断开连接的end节点
        for (int i = 1; i < k; i++) {
            if (end == null || end.next==null) {
                return phead.next;
            }
            end = end.next;
        }
       //断开end之前 保存end的下一个链表
        ListNode pre = end.next;
	  //断开end  
        end.next = null;
        //翻转start到end
        tail.next = rev(start);
	  //再让end变为下一个需要反转的链表开始节点
        end = pre;
	  //之前的start在反转后变为前一个链表的最后一个节点,则再其之后连接接下来反转的链表
        start.next = reverseKGroup(end, k);
    
        return phead.next;
    }

  //反转算法
    public ListNode rev(ListNode head) {
        ListNode phead = new ListNode(-1);
        phead.next = head;
        ListNode left = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode pre = cur.next;
            cur.next = left;
            left = cur;
            cur = pre;
        }
        return left;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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