LeetCode题解-25-Reverse Nodes in k-Group

原题

LeetCode题解-25-Reverse Nodes in k-Group_第1张图片


简介

该题共有2种解法,一种迭代,一种递归。


迭代法

解题思路

每一次取K个节点作为子链表,将其反转,然后将反转后的子链表添加到新的链表中。


图解

LeetCode题解-25-Reverse Nodes in k-Group_第2张图片

代码

public class Solution25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null || k <= 1)
            return  head;

        ListNode first, second, third;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode subHead = head, subTail, oldSubTail = dummy, nextSubHead;

        do {
            subTail = findSubTail(subHead ,k);

            if (subTail == null)
                break;
            else
                nextSubHead = subTail.next;

            reverseSubList(subHead, subTail);

            //更新标志位的值
            oldSubTail.next = subTail;
            oldSubTail = subHead;
            subHead = nextSubHead;
        }while (true);

        oldSubTail.next = subHead;
        return dummy.next;
    }

    private void reverseSubList(ListNode subHead, ListNode subTail) {
        ListNode first = subHead;
        ListNode second = first.next;
        first.next = null;
        while (first != subTail){
            ListNode third = (second == null) ? second : second.next;
            second.next = first;
            first = second;
            second = third;
        }
    }

    private ListNode findSubTail(ListNode subHead, int k) {
        ListNode subTail = subHead;
        for (int i = 1; i < k; i++) {
            subTail = (subTail == null) ? null : subTail.next;
        }
        return subTail;
    }
}


递归法

解题思路

Ⅰ、找到第K+1个节点,作为头节点递归,返回递归后的头节点curr;

Ⅱ、反转前K个节点并连接到curr;


代码

请参见:递归法

public ListNode reverseKGroup(ListNode head, int k) {
    ListNode curr = head;
    int count = 0;
    while (curr != null && count != k) { // find the k+1 node
        curr = curr.next;
        count++;
    }
    if (count == k) { // if k+1 node is found
        curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
        // head - head-pointer to direct part, 
        // curr - head-pointer to reversed part;
        while (count-- > 0) { // reverse current k-group: 
            ListNode tmp = head.next; // tmp - next head in direct part
            head.next = curr; // preappending "direct" head to the reversed list 
            curr = head; // move head of reversed part to a new node
            head = tmp; // move "direct" head to the next node in direct part
        }
        head = curr;
    }
    return head;
}




你可能感兴趣的:(LeetCode)