-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindromeLinkedList.cpp
84 lines (70 loc) · 1.83 KB
/
PalindromeLinkedList.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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int x) : data(x), next(nullptr) {}
};
bool isPalindrome(Node* head) {
if (!head || !head->next) {
return true;
}
//Find the middle of the linked list
Node *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
//Reverse the second half of the linked list
Node *prev = nullptr, *current = slow, *next = nullptr;
while (current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
// Second half is now reversed and `prev` is the head of this half
Node* secondHalf = prev;
//Compare the first half and the reversed second half
Node* firstHalf = head;
while (secondHalf) {
if (firstHalf->data != secondHalf->data) {
return false;
}
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
}
// Reverse the second half again to restore the original list
current = prev;
prev = nullptr;
while (current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return true;
}
void printList(Node* head) {
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(2);
head->next->next->next = new Node(1);
cout << "Original list: ";
printList(head);
if (isPalindrome(head)) {
cout << "The list is a palindrome." << endl;
} else {
cout << "The list is not a palindrome." << endl;
}
cout << "List after check: ";
printList(head);
return 0;
}