-
Notifications
You must be signed in to change notification settings - Fork 6
/
palindromeLL.cpp
111 lines (105 loc) · 1.55 KB
/
palindromeLL.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
101
102
103
104
105
106
107
108
109
110
111
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int data)
{
this->data=data;
next=NULL;
}
};
void print(Node* head)
{
if(head==NULL)
{
return;
}
cout<<head->data<<" ";
print(head->next);
}
Node* reverseLL(Node* head)
{
if(head==NULL || head->next==NULL)
{
return head;
}
Node* smallHead=reverseLL(head->next);
Node* temp=head->next;
temp->next=head;
head->next=NULL;
return smallHead;
}
Node* midPoint(Node* head)
{
Node* slow=head;
Node* fast=head->next;
while(fast!=NULL && fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
bool isPalindromeLL(Node* head)
{
if(head==NULL)
{
return true;
}
Node* temp1=head;
Node* mid=midPoint(head);
Node* temp2=mid->next;
mid->next=NULL;
temp2=reverseLL(temp2);
cout<<"Mid Node "<<mid->data<<endl;
print(temp2);
cout<<endl;
while(temp1 !=NULL && temp2!=NULL)
{
if(temp1->data != temp2->data)
{
return false;
}
temp1=temp1->next;
temp2=temp2->next;
}
return true; // If all fine;
}
Node* takeInput()
{
Node* head=NULL;
Node* tail=NULL;
int data;
cin>>data;
while(data!=-1)
{
Node* newNode=new Node(data);
if(head==NULL)
{
head=newNode;
tail=newNode;
}
else
{
tail->next=newNode;
tail=newNode;
}
cin>>data;
}
return head;
}
int main()
{
Node* head=takeInput();
if(isPalindromeLL(head))
{
cout<<"true"<<endl;
}
else
{
cout<<"false"<<endl;
}
}