Skip to content

Commit

Permalink
Added Rotate List
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 13, 2023
1 parent dec5946 commit f424acc
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -700,4 +700,15 @@ add_executable(RemoveDuplicatesFromSortedListII
target_link_libraries(
RemoveDuplicatesFromSortedListII
GTest::gtest_main
)

# Rotate List
add_executable(RotateList
Medium/RotateList/include/solution.hpp
Medium/RotateList/tests/test.cpp
)

target_link_libraries(
RotateList
GTest::gtest_main
)
59 changes: 59 additions & 0 deletions Medium/RotateList/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#pragma once

#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

struct ListNode {
int32_t value;
ListNode *next;
};

class Solution {
public:
static auto rotate_right(ListNode *head, int32_t k) -> ListNode* {
if (head == nullptr || k <= 0) return head;

int32_t length = get_length(head);
k %= length;
if (k == 0) return head;

ListNode* current = head;

for (int i = 0; i < length - k - 1; ++i) {
current = current->next;
}

ListNode* new_head = current->next;
current->next = nullptr;
current = new_head;

while (current->next != nullptr) {
current = current->next;
}

current->next = head;
return new_head;
}

static auto get_length(ListNode *node) -> int32_t {
int32_t count = 0;
while (node != nullptr) ++count, node = node->next;
return count;
}

static auto insert(ListNode **head_ref, int32_t new_value) -> void {
auto *node = new ListNode();
node->value = new_value;
node->next = (*head_ref);
(*head_ref) = node;
}

static auto print(ListNode *head) -> void {
while (head != nullptr) {
std::cout << head->value << ' ';
head = head->next;
}
}
};
17 changes: 17 additions & 0 deletions Medium/RotateList/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include "../include/solution.hpp"

auto main() -> int {
ListNode *node = nullptr;
Solution::insert(&node, 5);
Solution::insert(&node, 4);
Solution::insert(&node, 3);
Solution::insert(&node, 2);
Solution::insert(&node, 1);

Solution::print(node);
std::cout << '\n';
node = Solution::rotate_right(node, 2);
Solution::print(node);

return 0;
}

0 comments on commit f424acc

Please sign in to comment.