summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc
diff options
context:
space:
mode:
author3gg <3gg@shellblade.net>2025-02-05 18:36:31 -0800
committer3gg <3gg@shellblade.net>2025-02-05 18:36:31 -0800
commit4689e4e80b479be25f7557d05818f5caa723aafa (patch)
tree4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc
Initial commit.HEADmain
Diffstat (limited to 'top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc')
-rw-r--r--top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc63
1 files changed, 63 insertions, 0 deletions
diff --git a/top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc b/top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc
new file mode 100644
index 0000000..590c485
--- /dev/null
+++ b/top-interview-questions/easy/linked_list/05_palindrome_linked_list_2.cc
@@ -0,0 +1,63 @@
1/**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode() : val(0), next(nullptr) {}
7 * ListNode(int x) : val(x), next(nullptr) {}
8 * ListNode(int x, ListNode *next) : val(x), next(next) {}
9 * };
10 */
11class Solution {
12public:
13 // Return the length of the list.
14 size_t length(const ListNode* node) {
15 if (!node) return 0;
16 return 1 + length(node->next);
17 }
18
19 // Return the nth element of the list.
20 const ListNode* nth(const ListNode* node, size_t n) {
21 if (!node) return nullptr;
22 if (n == 0) return node;
23 return nth(node->next, n-1);
24 }
25
26 // Reverse the list up to, and not including, the nth element.
27 // Return the head of the reversed list (nth-1 node).
28 ListNode* reverse(ListNode* node, size_t n) {
29 if (!node) return nullptr;
30 if (!node->next) return node;
31 if (n == 1) {
32 node->next = nullptr;
33 return node;
34 }
35
36 ListNode* head = reverse(node->next, n-1);
37 node->next->next = node;
38 node->next = nullptr;
39 return head;
40 }
41
42 // Compare two lists for equality.
43 bool eq(const ListNode* a, const ListNode* b) {
44 if (!a && !b) return true;
45 if (!a) return false;
46 if (!b) return false;
47 if (a->val != b->val) return false;
48 return eq(a->next, b->next);
49 }
50
51 bool isPalindrome(ListNode* head) {
52 if (!head) return true;
53 if (!head->next) return true;
54
55 // If odd, get the middle element.
56 // If even, get the first element of the second half.
57 const size_t len = length(head);
58 const size_t middle = len/2;
59 const ListNode* head1 = nth(head, middle + (len & 1));
60 const ListNode* head2 = reverse(head, middle);
61 return eq(head1, head2);
62 }
63};