서하아빠의 개발 블로그

25. Reverse Nodes in k-Group 본문

알고리즘/LeetCode

25. Reverse Nodes in k-Group

서하아빠 2022. 5. 20. 14:10
Hard 

Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.

 

 

 

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]

Constraints:

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

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || k ==1) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        
        int totalNodes = 0;
        
        ListNode curr = head;
        
        while(curr!=null) {
            totalNodes++;
            curr = curr.next;
        }
        
        curr = head;
        ListNode next = null;
        ListNode prev = dummy;
        
        while(totalNodes>=k) {
            curr = prev.next;
            next = curr.next;
            
            for(int i=1; i<k; i++) {
                curr.next = next.next;
                next.next = prev.next;
                prev.next = next;
                next = curr.next;
            }
            
            prev = curr;
            totalNodes = totalNodes - k;
        }
        return dummy.next;
        
    }
}

'알고리즘 > LeetCode' 카테고리의 다른 글

121. Best Time to Buy and Sell Stock  (0) 2022.05.20
217. Contains Duplicate  (0) 2022.05.20
61. Rotate List  (0) 2022.05.19
200. Number of Islands  (0) 2021.06.14
693. Binary Number with Alternating Bits  (0) 2021.04.20