-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglyLinkedListIsPalidrome.cpp
66 lines (59 loc) · 1.14 KB
/
SinglyLinkedListIsPalidrome.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
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
};
int SinglyLinkedListIsPalindrome(ListNode *A)
{
if(A->next==NULL) return 1;
ListNode* curr=A,*prev=NULL,*next;
int c=0;
while(A!=NULL){
c++;
A=A->next;
}
A=curr;
c=c/2;
ListNode* left=A,*right;
while(c!=1){
left=left->next;
c--;
}
right=left->next;
left->next=NULL;
while(right!=NULL){
next=right->next;
right->next=prev;
prev=right;
right=next;
}
while(A!=NULL){
if (A->val != prev->val)
return 0;
prev=prev->next;
A=A->next;
}
return 1;
}
ListNode *createListFromIntegerN(int n) {
struct ListNode *head = NULL;
cout<<"Insert nodes into list \n";
for (int i = 0; i < n; i++) {
int new_data;
cin>>new_data;
ListNode *newnode = new(ListNode);
newnode->val = new_data;
newnode->next = head;
head = newnode;
}
return head;
}
int main()
{
int n;
cout<<"Enter the no. of nodes\n";
cin>>n;
cout <<"Result : "<< SinglyLinkedListIsPalindrome(createListFromIntegerN(n)) << endl;
return 0;
}