-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path243_Palindrome_LL.cpp
90 lines (78 loc) · 1.6 KB
/
243_Palindrome_LL.cpp
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
// LC - 234 Palindrome Linked List
// Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
// TC = O(n) SC =O(1)
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data) {
this-> data = data;
this -> next = NULL;
}
};
void insertAtTail(Node* &tail, int d) {
if(tail == NULL) {
Node* temp = new Node(d);
tail = temp;
}
else{
Node* temp = new Node(d);
tail -> next = temp;
tail = temp;
}
}
//reverse the middle half
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* curr = head;
Node* nextn;
while(curr != NULL) {
nextn = curr -> next;
curr -> next = prev;
prev = curr;
curr = nextn;
}
return prev;
}
bool isPalindrome(Node* head) {
//find the middle node
Node* slow = head;
Node* fast = head;
while(fast != NULL && fast -> next != NULL) {
slow = slow-> next;
fast = fast -> next -> next;
}
//after spliting in half reverse the half node
Node* secondHalf = reverseList(slow);
Node* p1 = head;
Node* p2 = secondHalf;
while(p2 != NULL) {
if(p2 -> data != p1-> data) {
return false;
}
p2 = p2-> next;
p1 = p1-> next;
}
return true;
}
void printList(Node* &head) {
Node* temp = head;
while(temp != NULL) {
cout << temp -> data << " ";
temp = temp-> next;
}
cout << endl;
}
int main() {
Node* node1 = new Node(1);
Node* tail = node1;
Node* head = node1;
insertAtTail(tail, 2);
insertAtTail(tail, 2);
insertAtTail(tail, 1);
printList(head);
cout << isPalindrome(head);
return 0;
}