-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCheck_LL_palindrome.cpp
79 lines (72 loc) · 1.48 KB
/
Check_LL_palindrome.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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
void forwardPrint(struct Node *head)
{
if (head == NULL)
return;
cout << head->data << " ";
forwardPrint(head->next);
}
Node *_last = NULL;
void insertEnd(struct Node **head, int data)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->data = data; // Insert data in new node
node->next = NULL; // link new node to NULL as it is last node
if (*head == NULL) // if list is empty add in beginning.
{
*head = node;
_last = node;
return;
}
_last->next = node; // Add the node after the last node of list
_last = node;
return;
}
/*
* struct Node {
* int data;
* Node *next;
* };
*
* The above structure defines the linked list node.
*/
int helper(struct Node **left, struct Node *right)
{
if (right == NULL)
return 1;
int result = helper(left, right->next);
if (result == 0)
return 0;
result = ((*left)->data == right->data);
*left = (*left)->next;
return result;
}
int checkPalindrome(struct Node *head)
{
return helper(&head, head);
}
int main()
{
int t, n, m;
cin >> t;
while (t--)
{
struct Node *head = NULL;
int ans;
cin >> n;
while (n--)
{
cin >> m;
insertEnd(&head, m);
}
ans = checkPalindrome(head);
cout << ans << endl;
}
return 0;
}