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.