Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update linked_list_palindrome.cpp #6730

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 29 additions & 21 deletions code/data_structures/src/Linked_List/linked_list_palindrome.cpp
@@ -1,24 +1,32 @@
// Check if the liked list is palindrome or not
bool checkpalindrome(vector<int> arr){
int s = 0;
int e = arr.size() -1;
while(s<=e){
if(arr[s] != arr[e]){
return 0;
}
s++;
e--;
}
return 1;
bool isPalindrome(Node* head) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do mention if you are making a specific improvement.

if (head == NULL || head->next == NULL) {
return true;
}
Node* additional = head;
Node* slow = head, * fast = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}

Node* np = slow;
Node* prev = slow, * curr = slow, * nex = slow;
curr = prev->next;
nex = curr->next;
while (nex != NULL) {
curr->next = nex->next;
nex->next = prev->next;
prev->next = nex;
nex = curr->next;
np = np->next;
}

bool isPalindrome(Node *head)
{
vector<int>arr;
Node* temp = head;
while(temp != NULL){
arr.push_back(temp -> data);
temp = temp -> next;
slow = slow->next;
while (slow != NULL) {
if (additional->val != slow->val) {
return false;
}
return checkpalindrome(arr);
additional = additional->next;
slow = slow->next;
}
return true;
}