File tree 1 file changed +114
-0
lines changed
1 file changed +114
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < map>
3
+
4
+ using namespace std ;
5
+
6
+ class Node {
7
+ public:
8
+ Node (){
9
+ next = NULL ;
10
+ }
11
+ // void setValue(int value){
12
+ // data = value;
13
+ // }
14
+ // int getValue(){
15
+ // return data;
16
+ // }
17
+ // private:
18
+ int data;
19
+ Node* next;
20
+ };
21
+
22
+ class LinkedList {
23
+ public:
24
+ LinkedList (){
25
+ head = NULL ;
26
+ }
27
+ void printAll ();
28
+ void insert_head (int );
29
+ void insert_front (int );
30
+ void setHead (Node*);
31
+ Node* getHead ();
32
+
33
+ private:
34
+ Node* head;
35
+
36
+ };
37
+
38
+ void LinkedList::setHead (Node* node){
39
+ this ->head = node;
40
+ }
41
+ Node* LinkedList::getHead (){
42
+ return this ->head ;
43
+ }
44
+ void LinkedList::insert_head (int value){
45
+ Node* node = new Node;
46
+ node->data = value;
47
+ node->next = head;
48
+ head = node;
49
+ }
50
+ void LinkedList::insert_front (int value){
51
+ Node* node = new Node;
52
+ if (head == NULL ){
53
+ head = node;
54
+ }
55
+ else {
56
+ Node* iter = head;
57
+ while (iter->next != NULL ){
58
+ iter = iter->next ;
59
+ }
60
+ iter->next = node;
61
+ }
62
+ node->data = value;
63
+ node->next = NULL ;
64
+ }
65
+ void LinkedList::printAll (){
66
+ Node* p;
67
+ p = head;
68
+ while (p != NULL ){
69
+ cout << p->data << endl;
70
+ p = p->next ;
71
+ }
72
+ cout << " -----" << endl;
73
+ }
74
+
75
+ bool is_palindrome_ll (LinkedList* l1){
76
+ Node* node = l1->getHead ();
77
+ int len = 0 ;
78
+ map<int , int > ht;
79
+
80
+ while (node != NULL ){
81
+ ht[node->data ] = ht[node->data ] + 1 ;
82
+ node = node->next ;
83
+ len += 1 ;
84
+ }
85
+ int has_visit_odd = len % 2 == 0 ? 1 : 0 ;
86
+
87
+ for (int i=0 ; i<ht.size (); i++){
88
+ if (ht[i] % 2 == 1 ){
89
+ if (has_visit_odd == 1 ){
90
+ return false ;
91
+ }
92
+ else {
93
+ has_visit_odd = 1 ;
94
+ }
95
+ }
96
+ }
97
+ return true ;
98
+ }
99
+
100
+ int main (){
101
+
102
+ LinkedList* l1 = new LinkedList;
103
+ l1->insert_front (2 );
104
+ l1->insert_front (3 );
105
+ l1->insert_front (5 );
106
+ l1->insert_front (5 );
107
+ l1->insert_front (3 );
108
+ l1->insert_front (2 );
109
+ l1->printAll ();
110
+ cout << is_palindrome_ll (l1) << endl;
111
+
112
+ return 0 ;
113
+ }
114
+
You can’t perform that action at this time.
0 commit comments