Skip to content

Commit

Permalink
Added Odd Even Linked List
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Oct 3, 2023
1 parent 2a6a5a7 commit bda7ae3
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1272,4 +1272,15 @@ add_executable(NumberOfGoodPairs
target_link_libraries(
NumberOfGoodPairs
GTest::gtest_main
)

# Odd Even Linked List
add_executable(OddEvenLinkedList
Medium/OddEvenLinkedList/include/solution.hpp
Medium/OddEvenLinkedList/tests/test.cpp
)

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

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

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

class Solution {
public:
static auto odd_even_list(ListNode *head) -> ListNode* {
if (head == nullptr) return nullptr;

ListNode *odd = head;
ListNode *even = head->next;
ListNode *even_head = head->next;

while (even && even->next) {
odd->next = odd->next->next;
even->next = even->next->next;
odd = odd->next;
even = even->next;
}

odd->next = even_head;
return head;
}

static auto insert(ListNode **head_ref,
const 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/OddEvenLinkedList/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::odd_even_list(node);
Solution::print(node);

return 0;
}

0 comments on commit bda7ae3

Please sign in to comment.