#21_ Day 21 (25)

Posted by marcth on Wed, 02 Feb 2022 16:14:37 +0100

I'll give you a linked list. Each group of k# nodes will be flipped. Please return to the flipped linked list.

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

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

Advanced:

Can you design an algorithm that only uses constant extra space to solve this problem?
You can't simply change the value inside the node, but you need to actually exchange nodes.
 

Example 1:


Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:


Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Example 3:

Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]
Example 4:

Input: head = [1], k = 1
Output: [1]
Tips:

The number of nodes in the list is within sz range
1 <= sz <= 5000
0 <= Node.val <= 1000
1 <= k <= sz

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

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        dummy = ListNode(0)
        p = dummy
        while True:
            count = k 
            stack = []
            tmp = head
            while count and tmp:
                stack.append(tmp)
                tmp = tmp.next
                count -= 1
            # Note that the current position of tmp is k+1
            # Note that the remaining linked list is not enough k, jump out of the loop
            if count : 
                p.next = head
                break
            # Flip operation
            while stack:
                p.next = stack.pop()
                p = p.next
            #Connect with the rest of the linked list 
            p.next = tmp
            head = tmp
        
        return dummy.next

Idea:

Seeing the problem stem, I found that the problem is solved through two parts. The first part is to turn the function, which has many methods. The second part is to group the linked list, and then splice the turned part with the rest.

After thinking, it is found that the implementation of the second part is relatively simple. It is nothing more than setting a counter and resetting k times per jump. As for the splicing part, it is also to point the head and tail of the inverted linked list to the connecting point of the finger respectively.

Flip method:

(refer to the comment area of Likou)

1. Stack method:

By putting the connecting points into the stack one by one and then popping up, you can naturally get a flipped linked list.

2. Tail interpolation method:

for instance:
1 2 3 4

2 3 4 1

3 4 2 1

4 3 2 1

That is, insert the head node into the back of the first tail node in turn to get the flipped linked list naturally.

3. Exchange method:

If the length of the linked list is even, we only need to exchange the head and tail. Each time, the head node moves backward and the tail node moves forward until they are equal.

If the length of the linked list is odd, exit when the two pointers refer to the same area.

4. Simulation method:
code:

class Solution:
    # Flip a sub linked list and return the new head and tail
    def reverse(self, head: ListNode, tail: ListNode):
        prev = tail.next
        p = head
        while prev != tail:
            nex = p.next
            p.next = prev
            prev = p
            p = nex
        return tail, head

    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        hair = ListNode(0)
        hair.next = head
        pre = hair

        while head:
            tail = pre
            # Check whether the length of the remaining part is greater than or equal to k
            for i in range(k):
                tail = tail.next
                if not tail:
                    return hair.next
            nex = tail.next
            head, tail = self.reverse(head, tail)
            # Reconnect the sub linked list to the original linked list
            pre.next = head
            tail.next = nex
            pre = tail
            head = tail.next
        
        return hair.next

Author: LeetCode-Solution
 Link: https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/k-ge-yi-zu-fan-zhuan-lian-biao-by-leetcode-solutio/
Source: force buckle( LeetCode)

This method is taken from the force buckle. For the turning part, four pointers are used. In order to avoid considering complex situations, four pointers and a dummy point are used.

Topics: leetcode