leetcode第25题:K个一组反转链表

Java 实现

一。使用双指针,start指针指向要反转的区间的第一个元素,end指针指向反转区间的最后一个元素,有多少个长度为K的区间就反转多少个区间,反转的逻辑用reverse()函数来实现。
二。反转的时候注意不要出现回环或者空指针即可。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode start = head, end = head;
        int count = 1;
        //前一个区间的尾节点,用于连接后一个区间
        ListNode pre = null;
        while(start != null){
            while(end != null && count < k){
                end = end.next;
                count++;
            }
            //区间长度不足k,一定是最后一个区间,不用反转,直接返回
            if(end == null) return dummy.next;
            if(start == head) dummy.next = end;
            ListNode temp = end.next;
            ListNode cur = reverse(start, end, k);
            if(start != head) pre.next = cur;
            count = 1;
            pre = start;
            start = temp;
            end = temp;
        }
        return dummy.next;
    }
    //根据区间的开始和结尾,以及区间的长度进行反转
    public ListNode reverse(ListNode start, ListNode end, int k){
        int count = 1;
        ListNode cur = start;
        ListNode temp1 = end.next;
        ListNode temp2 = null;
        while(count <= k){
            temp2 = cur.next;
            cur.next = temp1;
            temp1 = cur;
            cur = temp2;
            count++;
        }
        return temp1 ;
    }
}


作者:tan-78
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/javanao-can-jie-fa-shuang-zhi-zhen-by-tan-78/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/tandejian/p/12902137.html
今日推荐