Skip to content

Commit 2ce3a21

Browse files
Add files via upload
1 parent 2af724d commit 2ce3a21

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

CheckIfLinkedListIsPalindrome.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Given a singly linked list of size N of integers. The task is to check if the given linked list is palindrome or not.
3+
4+
Example 1:
5+
Input:
6+
N = 3
7+
value[] = {1,2,1}
8+
Output: 1
9+
Explanation: The given linked list is
10+
1 2 1 , which is a palindrome and
11+
Hence, the output is 1.
12+
13+
Example 2:
14+
Input:
15+
N = 4
16+
value[] = {1,2,3,4}
17+
Output: 0
18+
Explanation: The given linked list
19+
is 1 2 3 4 , which is not a palindrome
20+
and Hence, the output is 0.
21+
Your Task:
22+
The task is to complete the function isPalindrome() which takes head as reference as the only parameter and returns true or false if linked list is palindrome or not respectively.
23+
24+
Expected Time Complexity: O(N)
25+
Expected Auxialliary Space Usage: O(1) (ie, you should not use the recursive stack space as well)
26+
*/
27+
28+
/// No Linear Extra Space
29+
30+
class Solution{
31+
public:
32+
//Function to reverse the LL
33+
Node* makeReverse(Node *head){
34+
if(!head or !head->next) return head;
35+
Node *reverse=makeReverse(head->next);
36+
head->next->next=head;
37+
head->next=NULL;
38+
return reverse;
39+
}
40+
41+
//Function to check whether the list is palindrome.
42+
bool isPalindrome(Node *head)
43+
{
44+
if(!head or !head->next) return true;
45+
Node *slow=head;
46+
Node *fast=head->next;
47+
while(fast and fast->next){
48+
slow=slow->next;
49+
fast=fast->next->next;
50+
}
51+
Node *reverse=makeReverse(slow->next);
52+
slow=head;
53+
while(slow and reverse){
54+
if(slow->data!=reverse->data) return false;
55+
slow=slow->next;
56+
reverse=reverse->next;
57+
}
58+
return true;
59+
}
60+
};

0 commit comments

Comments
 (0)