25. Reverse Nodes in k-Group

Description

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Solution

Iterative

蛮有意思的题,最初觉得就是reverse一整条list的变种,后来发现不太一样,思路被打开了。常规reverse list的写法是用双指针法,边移动指针边修改指针指向前面的节点。但其实还有另外一种思路,就是边扫描边将当前节点插入到链表头部。这种思路是比较好应用到本题上的。

25. Reverse Nodes in k-Group_第1张图片
/**
 * 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) {
        if (head == null || head.next == null || k < 2) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        int len = getLength(head);
        ListNode prevTail = dummy;

        while (k <= len) {
            ListNode prev = prevTail.next;
            for (int i = 0; i < k - 1; ++i) {
                ListNode curr = prev.next;
                prev.next = curr.next;
                curr.next = prevTail.next;
                prevTail.next = curr;
            }

            prevTail = prev;
            len -= k;
        }

        return dummy.next;
    }

    public int getLength(ListNode head) {
        int len = 0;
        while (head != null) {
            ++len;
            head = head.next;
        }
        return len;
    }
}

Recursive

/**
 * 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) {
        if (head == null || head.next == null || k < 2) {
            return head;
        } 
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        int len = getLength(head);
        reverseKGroupRecur(dummy, k, len);
        return dummy.next;
    }

    public void reverseKGroupRecur(ListNode prevTail, int k, int len) {
        if (len < k) {
            return;
        }

        ListNode prev = prevTail.next;
        for (int i = 0; i < k - 1; ++i) {
            ListNode curr = prev.next;
            prev.next = curr.next;
            curr.next = prevTail.next;
            prevTail.next = curr;
        }
        reverseKGroupRecur(prev, k, len - k);
    }
    
    public int getLength(ListNode head) {
        int len = 0;
        while (head != null) {
            ++len;
            head = head.next;
        }
        return len;
    }
}

你可能感兴趣的:(25. Reverse Nodes in k-Group)