LeetCode Reverse Nodes in k-Group

Source: Internet
Author: User

LeetCode Reverse Nodes in k-Group
LeetCode-solving-Reverse Nodes in k-Group original question

Flip the number of each k in a linked list without changing the number of k at the end.

Note:

Node values cannot be modified. Only the extra space of constants can be used.

Example:

Input: head = 1-> 2-> 3-> 4-> 5, k = 2
Output: 2-> 1-> 4-> 3-> 5

Input: head = 1-> 2-> 3-> 4-> 5, k = 3
Output: 3-> 2-> 1-> 4-> 5

Solutions

This is an upgraded version of Swap Nodes in Pairs. Let's take A look at the operations to flip k nodes, A-> B-> C-> D-> E. Now we need to flip BCD three nodes. Perform the following steps:

C-> BD-> CB-> EA-> D Return and Node B

We did two things above. We first flipped the k nodes (Steps 1 and 2) and connected them to the two nodes (Steps 3 and 4 ).

AC Source Code
# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def reverseKGroup(self, head, k):        """        :type head: ListNode        :type k: int        :rtype: ListNode        """        if not head or k <= 1:            return head        dummy = ListNode(-1)        dummy.next = head        temp = dummy        while temp:            temp = self.reverseNextK(temp, k)        return dummy.next    def reverseNextK(self, head, k):        # Check if there are k nodes left        temp = head        for i in range(k):            if not temp.next:                return None            temp = temp.next        # The last node when the k nodes reversed        node = head.next        prev = head        curr = head.next        # Reverse k nodes        for i in range(k):            nextNode = curr.nex            curr.next = prev            prev = curr            curr = nextNode        # Connect with head and tail        node.next = curr        head.next = prev        return node

Please check out my Github for relevant source code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.