Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 도메인 #도메인 주도 설계 #도메인 주도 설계 핵심 #DDD
- leetcode #20. Valid Parentheses #알고리즘 #leetcode Valid Parentheses
- codinGame
- leetcode #알고리즘 #릿코드
- 코딩게임
- 867. Transpose Matrix #Transpose Matrix
- #move zeroes
- base7
- aws #cloudwatch #log insight
- DDD #도메인 #도메인 주도 설계 #도메인 주도 설계 핵심
- 도메인 주도 설계 핵심
- DDD #도메인 #도메인 주도 설계 #도메인 주도 섥계 핵심
- codingame #코딩게임 #codingame fall challenge2023 #코딩게임 2023 가을 챌린지
- Fall Challenge 2023
- leetcode #2206. Divide Array Into Equal Pairs
- 도메인 주도 설계 핵심 #DDD #도메인 주도 설계 #도메인
- #20. Valid Parentheses java
- LeetCode #
- ddd
- Find Pivot Index
- leetcode
- 반 버논
Archives
- Today
- Total
서하아빠의 개발 블로그
25. Reverse Nodes in k-Group 본문
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 |