-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathPalindrome_linked_list.cpp
More file actions
94 lines (85 loc) · 1.77 KB
/
Palindrome_linked_list.cpp
File metadata and controls
94 lines (85 loc) · 1.77 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
#include <bits/stdc++.h>
using namespace std;
struct node{
char data;
node *next;
};
node *get(char ch){
node *Temp = new node();
Temp -> data = ch;
Temp -> next = NULL;
return Temp;
}
node *insert(node *root , char ch){
if(root == NULL)
return get(ch);
node *temp = get(ch);
temp -> next = root;
return temp;
}
void print(node *root){
while(root){
cout << root -> data << " ";
root = root -> next;
}
}
node * reverse(node *root){
node *prev = NULL , *cur = root , *next = NULL;
while(cur != NULL){
next = cur -> next;
cur -> next = prev;
prev = cur;
cur = next;
}
root = prev;
return root;
}
bool check(node *root){
node *slow = root , *fast = root;
node *prev = NULL;
if(root == NULL)return false; // No node;
if(root -> next == NULL )return true; // single node;
while(fast != NULL && fast->next != NULL){
fast = fast -> next -> next;
prev = slow;
slow = slow -> next;
}
node *head2 = NULL;
if(fast != NULL){ // odd
head2 = slow -> next;
slow -> next = NULL;
}
else
head2 = prev -> next;
prev -> next = NULL;
head2 = reverse(head2);
node *Slow = root;
node *Fast = head2;
bool ok = true;
while(Fast != NULL && Slow != NULL){
if(Fast -> data != Slow -> data){
ok = false;
break;
}
Fast = Fast -> next ;
Slow = Slow -> next;
}
head2 = reverse(head2);
if(fast != NULL){
slow -> next = head2;
prev -> next = slow;
}
else
prev -> next = head2;
return ok;
}
int main(){
char arr[100];
cin >> arr;
int i = 0;
node *root = NULL;
while(arr[i]){
root = insert(root , arr[i++]);
}
puts(check(root) ? "Palindrom" : "NOT Palindrom");
}