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
4
using namespace
std;
5
9
struct
ListNode
10
{
11
int
val
;
12
ListNode
*
next
;
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
18
class
Solution
19
{
20
public
:
21
bool
isPalindrome
(
ListNode
* head)
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
51
void
delete_list
(
ListNode
* ptr)
52
{
53
ListNode
* tmp = ptr->
next
;
54
if
(tmp)
55
delete_list
(tmp);
56
delete
ptr;
57
}
58
59
int
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
}
Solution
Definition
main.cpp:19
Solution::isPalindrome
bool isPalindrome(ListNode *head)
Definition
main.cpp:21
main
int main()
Definition
main.cpp:59
delete_list
void delete_list(ListNode *ptr)
Definition
main.cpp:51
ListNode
Definition for singly-linked list.
Definition
main.cpp:10
ListNode::val
int val
Definition
main.cpp:11
ListNode::ListNode
ListNode(int x)
Definition
main.cpp:14
ListNode::ListNode
ListNode()
Definition
main.cpp:13
ListNode::next
ListNode * next
Definition
main.cpp:12
ListNode::ListNode
ListNode(int x, ListNode *next)
Definition
main.cpp:15
main.cpp
Generated by
1.9.8