leetcode25——K 个一组翻转链表——java实现

题目要求:
在这里插入图片描述
分析:
这道题目包含链表反转,所以可以调用反转链表那道题目。传送门:反转链表

既然知道如何反转链表,那么只需要对整个链表根据k来进行断开即可。

断开之后,调用反转链表方法,再将后面的接上,如此循环,直到最后。

在这里,要注意的一点有:如果节点总数不为k的整数倍,则保持原有顺序。

具体思路如下图:
在这里插入图片描述

具体代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node1 = dummy;
        ListNode node2 = dummy;
        while(node2.next != null) {
             for(int i = 0; i < k; i++) {
                if(node2 == null)
                    break;
                node2 = node2.next;
            }
            if(node2 == null)
                break;
            ListNode start = node1.next;
            ListNode nextRegion = node2.next;
            node2.next = null;
            node1.next = reverseList(start);
            start.next = nextRegion;
            node1 = start;
            node2 = node1;
        }
       return dummy.next;
    }

    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode pre = null;
        ListNode curr = head;
        ListNode temp = new ListNode(0);
        while(curr != null) {
            temp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = temp;
        }
        return pre;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值