25. Reverse Nodes in k-Group

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了25. Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list‘s nodes, only nodes itself may be changed.

解题思路:https://leetcode.windliang.cc/leetCode-25-Reverse-Nodes-in-k-Group.html

public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null)
        return null;
    ListNode sub_head = head;
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode tail = dummy;
    ListNode toNull = head;
    while (sub_head != null) {
        int i = k;
        //找到子链表的尾部
        while (i - 1 > 0) {
            toNull = toNull.next;
            if (toNull == null) {
                return dummy.next;
            }
            i--;
        }
        ListNode temp = toNull.next;
        //将子链表断开
        toNull.next = null;
        ListNode new_sub_head = reverse(sub_head); 
        //将倒置后的链表接到 tail 后边
        tail.next = new_sub_head;
        //更新 tail 
        tail = sub_head; //sub_head 由于倒置其实是新链表的尾部
        sub_head = temp;
        toNull = sub_head;
        //将后边断开的链表接回来
        tail.next = sub_head;
    }
    return dummy.next;
}
public ListNode reverse(ListNode head) {
    ListNode current_head = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = current_head;
        current_head = head;
        head = next;
    }
    return current_head;
}

很好很强大,我很饿

以上是关于25. Reverse Nodes in k-Group的主要内容,如果未能解决你的问题,请参考以下文章

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group(js)

LeetCode - 25. Reverse Nodes in k-Group