diff options
Diffstat (limited to 'top-interview-questions/easy/linked_list/05_palindrome_linked_list.cc')
-rw-r--r-- | top-interview-questions/easy/linked_list/05_palindrome_linked_list.cc | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/top-interview-questions/easy/linked_list/05_palindrome_linked_list.cc b/top-interview-questions/easy/linked_list/05_palindrome_linked_list.cc new file mode 100644 index 0000000..3f42e4a --- /dev/null +++ b/top-interview-questions/easy/linked_list/05_palindrome_linked_list.cc | |||
@@ -0,0 +1,48 @@ | |||
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 | */ | ||
11 | class Solution { | ||
12 | public: | ||
13 | // Copy the list. | ||
14 | ListNode* clone(const ListNode* node) { | ||
15 | if (!node) return nullptr; | ||
16 | ListNode* copy = new ListNode(); | ||
17 | copy->val = node->val; | ||
18 | if (node->next) { | ||
19 | copy->next = clone(node->next); | ||
20 | } else { | ||
21 | copy->next = nullptr; | ||
22 | } | ||
23 | return copy; | ||
24 | } | ||
25 | |||
26 | // Reverse a list and return the new of the reversed list. | ||
27 | ListNode* reverse(ListNode* node) { | ||
28 | if (!node) return nullptr; | ||
29 | if (!node->next) return node; | ||
30 | ListNode* head = reverse(node->next); | ||
31 | node->next->next = node; | ||
32 | node->next = nullptr; | ||
33 | return head; | ||
34 | } | ||
35 | |||
36 | // Compare two lists for equality. | ||
37 | bool eq(const ListNode* a, const LideNode* b) { | ||
38 | if (!a && !b) return true; | ||
39 | if (!a) return false; | ||
40 | if (!b) return false; | ||
41 | if (a->val != b->val) return false; | ||
42 | return eq(a->next, b->next); | ||
43 | } | ||
44 | |||
45 | bool isPalindrome(ListNode* head) { | ||
46 | return eq(head, reverse(clone(head))); | ||
47 | } | ||
48 | }; | ||