-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathll_palindrome.cpp
More file actions
114 lines (101 loc) · 1.68 KB
/
ll_palindrome.cpp
File metadata and controls
114 lines (101 loc) · 1.68 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <map>
using namespace std;
class Node{
public:
Node(){
next = NULL;
}
//void setValue(int value){
// data = value;
//}
//int getValue(){
// return data;
//}
//private:
int data;
Node* next;
};
class LinkedList{
public:
LinkedList(){
head = NULL;
}
void printAll();
void insert_head(int);
void insert_front(int);
void setHead(Node*);
Node* getHead();
private:
Node* head;
};
void LinkedList::setHead(Node* node){
this->head = node;
}
Node* LinkedList::getHead(){
return this->head;
}
void LinkedList::insert_head(int value){
Node* node = new Node;
node->data = value;
node->next = head;
head = node;
}
void LinkedList::insert_front(int value){
Node* node = new Node;
if(head == NULL){
head = node;
}
else{
Node* iter = head;
while(iter->next != NULL){
iter = iter->next;
}
iter->next = node;
}
node->data = value;
node->next = NULL;
}
void LinkedList::printAll(){
Node* p;
p = head;
while(p != NULL){
cout << p->data << endl;
p = p->next;
}
cout << "-----" << endl;
}
bool is_palindrome_ll(LinkedList* l1){
Node* node = l1->getHead();
int len = 0;
map<int, int> ht;
while(node != NULL){
ht[node->data] = ht[node->data] + 1;
node = node->next;
len += 1;
}
int has_visit_odd = len % 2 == 0 ? 1 : 0;
for(int i=0; i<ht.size(); i++){
if(ht[i] % 2 == 1){
if(has_visit_odd == 1){
return false;
}
else{
has_visit_odd = 1;
}
}
}
return true;
}
int main(){
LinkedList* l1 = new LinkedList;
l1->insert_front(2);
l1->insert_front(3);
l1->insert_front(5);
l1->insert_front(5);
l1->insert_front(3);
l1->insert_front(2);
l1->printAll();
cout << is_palindrome_ll(l1) << endl;
return 0;
}