algorithm/leetcode

Reverse Nodes in k-Group [LeetCode]

hoonzii 2021. 7. 18. 20:15
반응형

문제 풀이 정리

 

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.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

 

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]

 

Constraints:

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

코드

# 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:
        
        num_list = []
        while head.next:
            num_list.append(head.val)
            head = head.next
        num_list.append(head.val)
        
        reverse_num = len(num_list) // k
        start = 0
        end = k
        modi_list = []
        for _ in range(reverse_num):
            for index in range(end-1, start-1, -1):
                modi_list.append(num_list[index])
            if end+k > len(num_list):
                break
            start += k
            end += k
        
        modi_list.extend(num_list[end:len(num_list)])
        
        head = ListNode(modi_list[0], None)
        for index in range(1, len(modi_list)):
            node = ListNode(modi_list[index], None)
            
            temp_node = head
            while temp_node.next != None:
                temp_node = temp_node.next
            temp_node.next = node
        
        return head

문제 넋두리

어려워 보이지 않아서 도전쓰 & 성공~

영어 문제 이제 익숙해지는 건가?

응 아니다...

입력으로 주어지는 k 만큼 뒤집어 주면되는 문제, 별로 어렵지 않았지만

아직 파이썬 LinkedList 문제의 경우 next 연결 시켜주는게 헷갈려서 헤맸다.

반응형