Skip to content

Commit

Permalink
Added Palindrome Linked List
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 10, 2023
1 parent 55139b7 commit 7071f83
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 9 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -667,4 +667,15 @@ add_executable(ReverseLinkedListII
target_link_libraries(
ReverseLinkedListII
GTest::gtest_main
)

# Palindrome Linked List
add_executable(PalindromeLinkedList
Easy/PalindromeLinkedList/include/solution.hpp
Easy/PalindromeLinkedList/tests/test.cpp
)

target_link_libraries(
PalindromeLinkedList
GTest::gtest_main
)
53 changes: 47 additions & 6 deletions Easy/PalindromeLinkedList/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,49 @@
//
// Created by draco on 9/12/23.
//
#pragma once

#ifndef LEETCODEJOURNEY_SOLUTION_HPP
#define LEETCODEJOURNEY_SOLUTION_HPP
#include <ranges>
#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

#endif //LEETCODEJOURNEY_SOLUTION_HPP
struct ListNode {
int32_t value;
ListNode *next;
};

class Solution {
public:
static auto is_palindrome(ListNode *head) -> bool {
std::vector<int32_t> numbers;

while (head != nullptr) {
numbers.emplace_back(head->value);
head = head->next;
}

std::size_t left = 0;
std::size_t right = numbers.size() - 1;

while (left < right) {
if (numbers[left] != numbers[right]) {
return false;
} ++left, --right;
}

return true;
}

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;
}
}
};
16 changes: 13 additions & 3 deletions Easy/PalindromeLinkedList/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
//
// Created by draco on 9/12/23.
//
#include "../include/solution.hpp"

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

std::cout << std::boolalpha << Solution::is_palindrome(head);

return 0;
}

0 comments on commit 7071f83

Please sign in to comment.