palindrome-linked-list 1.0.0
Palindrome Linked List
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <deque>
3
4using namespace std;
5
9struct ListNode
10{
11 int val;
13 ListNode() : val(0), next(nullptr) {}
14 ListNode(int x) : val(x), next(nullptr) {}
15 ListNode(int x, ListNode *next) : val(x), next(next) {}
16};
17
19{
20public:
22 {
23 ListNode* ptr = head;
24 deque<ListNode*> queue;
25 while (ptr != NULL)
26 {
27 queue.push_back(ptr);
28 ptr = ptr->next;
29 }
30 // for (ListNode* node: queue)
31 // cout << "Node val: " << node->val << endl;
32 while (!queue.empty())
33 {
34 // odd word length
35 ListNode* upper = queue.front();
36 ListNode* lower = queue.back();
37 if (upper == lower)
38 return true; // all characters are processed, only middle one left, e.g. r in waraw is both upper and lower
39
40 // even word length
41 if (upper->val != lower->val)
42 return false;
43
44 queue.pop_front();
45 queue.pop_back();
46 }
47 return true; // all characters are processed, e.g. wawa
48 }
49};
50
52{
53 ListNode* tmp = ptr->next;
54 if (tmp)
55 delete_list(tmp);
56 delete ptr;
57}
58
59int main()
60{
61 ListNode* head = new ListNode(0, new ListNode(1, new ListNode(1, new ListNode(0, NULL))));
62 Solution sol;
63 bool result = sol.isPalindrome(head);
64 if (result)
65 cout << "The list is a palindrome" << endl;
66 else
67 cout << "The list is not a palindrome" << endl;
68 delete_list(head);
69 return 0;
70}
bool isPalindrome(ListNode *head)
Definition main.cpp:21
int main()
Definition main.cpp:59
void delete_list(ListNode *ptr)
Definition main.cpp:51
Definition for singly-linked list.
Definition main.cpp:10
int val
Definition main.cpp:11
ListNode(int x)
Definition main.cpp:14
ListNode()
Definition main.cpp:13
ListNode * next
Definition main.cpp:12
ListNode(int x, ListNode *next)
Definition main.cpp:15