-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist_palindrome.h
More file actions
57 lines (49 loc) · 1.32 KB
/
Copy pathlist_palindrome.h
File metadata and controls
57 lines (49 loc) · 1.32 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#ifndef CPP_ALGORITHM_LIST_PALINDROME_H
#define CPP_ALGORITHM_LIST_PALINDROME_H
#include "linked_list.h"
namespace ListPalindrome
{
/**
* \brief Check if a singly linked list is a palindrome.
* \param list the head of the list
* \return whether the list is a palindrome
*/
bool IsListPalindrome(
const std::shared_ptr<LinkedList::Node<int>>& list);
}
// ----------------------------------------------------------------------------
inline bool ListPalindrome::IsListPalindrome(
const std::shared_ptr<LinkedList::Node<int>>& list)
{
// Find the middle of the list
auto slow = list;
auto fast = list;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
// Reverse the second half of the list
std::shared_ptr<LinkedList::Node<int>> later = nullptr;
while (slow)
{
const auto temp = slow->next;
slow->next = later;
later = slow;
slow = temp;
}
// Compare the first and second halves of the list
auto first_half = list;
auto second_half = later;
while (second_half)
{
if (first_half->data != second_half->data)
{
return false;
}
first_half = first_half->next;
second_half = second_half->next;
}
return true;
}
#endif