[Algorithmic Daily] K sets of inverted chains

Keywords: Python less REST

K sets of flip chains

Title Source: LeetCode
Links: https://leetcode-cn.com/problems/reverse-nodes-in-k-group

Give you a list of links that are flipped in groups of k nodes. Please return to the flipped list.

k is a positive integer whose value is less than or equal to the length of the chain table.

If the total number of nodes is not an integer multiple of k, keep the last remaining nodes in their original order.

Example:

Given this list: 1->2->3->4->5

When k = 2, it should return: 2->1->4->3->5

When k = 3, it should return: 3->2->1->4->5

Explain:

Your algorithm can only use a constant amount of extra space.
You can't simply change the value inside a node, you need to actually exchange nodes.

Problem

1. Subchains of every k length that a list of chains needs to be flipped are considered as a whole, that is, a list of chains Inverse Chain List Questions.
2. The rest of the concern is to connect the inverted sublist to the total list, so you need to find the front node, the back node, and the start and end node of the inverted sublist.
3. After the reverse operation is completed, connect the node in front of the reverse chain list to the start position of the reverse chain list, and the node in the end position after the reverse to the node in the group that needs to reverse the chain list, so the reverse is completed.By analogy until the length of the chain list to be inverted is less than k, the operation of K sets of inverted chain lists is completed.
Time complexity is O(n) and space complexity is O(1)

The code is as follows:

# -*- coding: utf-8 -*-
# @Author   : xaohuihui
# @Time     : 19-12-13
# @File     : reverse_nodes_k_group.py
# Software  : study

"""
K A set of flip chains
"""

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def reverse_list(head: ListNode) -> ListNode:
    new_node = None
    while head:
        p = head.next          # Stay next node
        head.next = new_node   # head points to the previous node. The previous node starts with None
        new_node = head        # new_node moves backward to the current head er location
        head = p               # head moves a node backward
    if not new_node:
        return head
    else:
        return new_node

def reverse_k_group(head: ListNode, k: int) -> ListNode:
    if head and head.next:
        pre = ListNode(0)
        pre.next = head                         # Request a new node, record the starting position, and return to the flipped first node at the end
        tmp = pre
        while tmp and tmp.next:
            i = 1
            start = end = tmp.next              # Request start and end pointers to initialize the header node location where this group needs to flip the chain table
            while i < k and end.next:           # The purpose of this loop is to point the end pointer to the last place in the group where the list of chains needs to be flipped
                end = end.next
                i += 1
            if i == k:                          # If this group needs to flip the list to a length of k, proceed
                last = end.next                 # LastRecord the position of the head node at the back of the chain table that this group needs to flip
                end.next = None                 # Set the next of the last node of your list that this group needs to flip to None for easy flipping
                tmp.next = reverse_list(start)  # Returns the head node of the linked list after exchange, so that the next of the last node of the front linked list in the group that needs to flip the linked list points to the flipped head node
                start.next = last               # Point the next pointer of the flipped last node to the node behind the flipped list in this group, so that the flipped list is connected to the original list

                tmp = start                     # Point the tmp pointer to the next set of nodes that need to flip the front of the chain table
            else:                               # If the length of this set of chains does not conform to k, no exchange is made, indicating that the exchange is complete and returning to the node behind the exchange
                return pre.next
        return pre.next
    else:
        return head

if __name__ == '__main__':
    node1 = ListNode(1)
    node2 = ListNode(2)
    node3 = ListNode(3)
    node4 = ListNode(4)
    node5 = ListNode(5)

    node1.next = node2
    node2.next = node3
    node3.next = node4
    node4.next = node5

    k = 2

    res = reverse_k_group(node1, k)
    while res:
        print(res.val)
        res = res.next

Output results:

2
1
4
3
5

Posted by misfits on Sat, 14 Dec 2019 00:22:24 -0800