-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome_Linked_List.cpp
100 lines (78 loc) · 2.17 KB
/
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
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
95
96
97
98
99
100
/* Problem Given the head of a Singly LinkedList, write a method to check if the LinkedList is a palindrome or not.*/
/*Naive Approach is to copy elements of linked list to a vector and check for palindrome
TimeComplexity taken is O(N)+O(N) (For travesing through linked list and checking for palindrome in vector
Space Complexity taken is O(N)
Let's solve this problem in constant space!! as below
*/
#include<iostream>
using namespace std;
class ListNode
{
public:
int value=0;
ListNode* next;
ListNode(int value)
{
this->value=value;
next=nullptr;
}
};
class Palindrome_Linked_List
{
public:
static bool Is_Palindrome_Linked_List(ListNode* head)
{
if(head->next==nullptr || head==nullptr)
{
return true;
}
// Find Middle of linked list
ListNode *fastpointer=head;
ListNode *slowpointer=head;
while(fastpointer!=nullptr && fastpointer->next!=nullptr)
{
fastpointer=fastpointer->next->next;
slowpointer=slowpointer->next;
}
ListNode *headofsecondhalf=reverse(slowpointer);
ListNode *copyofheadofsecondhalf=headofsecondhalf;
while(head!=nullptr && headofsecondhalf!=nullptr)
{
if(head->value!=headofsecondhalf->value)
{
break;
}
head=head->next;
headofsecondhalf=headofsecondhalf->next;
}
reverse(copyofheadofsecondhalf);
if(head==nullptr || headofsecondhalf==nullptr)
{
return true;
}
return false;
}
private:
static ListNode* reverse(ListNode* head)
{
ListNode* prev=nullptr;
while(head!=nullptr)
{
ListNode* next=head->next;
head->next=prev;
prev=head;
head=next;
}
return prev;
}
};
int main()
{
ListNode* head=new ListNode(1);
head->next=new ListNode(2);
head->next->next= new ListNode(3);
head->next->next->next=new ListNode(2);
head->next->next->next->next= new ListNode(1);
/* head->next->next->next->next->next= new ListNode(4);*/
cout<<Palindrome_Linked_List::Is_Palindrome_Linked_List(head);
}