-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome_Linked_List.cpp
52 lines (43 loc) · 1003 Bytes
/
Palindrome_Linked_List.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
LinkedListNode<int> *reverse(LinkedListNode<int> *head)
{
LinkedListNode<int> *curr = head;
LinkedListNode<int> *prev = NULL;
while (curr != NULL)
{
LinkedListNode<int> *n = curr->next;
curr->next = prev;
prev = curr;
curr = n;
}
return prev;
}
bool isPalindrome(LinkedListNode<int> *head)
{
// LinkedListNode<int> * newh=reverse(head);
if (head == NULL)
{
return true;
}
LinkedListNode<int> *slow = head;
LinkedListNode<int> *fast = head->next;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
LinkedListNode<int> *newh = slow->next;
slow->next = NULL;
newh = reverse(newh);
LinkedListNode<int> *temp = head;
while (newh != NULL && temp != NULL)
{
if (temp->data != newh->data)
{
return false;
}
newh = newh->next;
temp = temp->next;
}
return true;
return true;
}