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

Created linked_list_is_palindrome #453

Merged
merged 2 commits into from Dec 15, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Create linked_list_is_palindrome
  • Loading branch information
atendstowards0 committed Oct 1, 2020
commit 478f2215887c126d62b80b8490e6e608c0fa492d
60 changes: 60 additions & 0 deletions LinkedList/linked_list_is_palindrome
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
int data;
Node(int d){
data = d;
}
Node *ptr;
};

bool isPalindrome(Node* head){ // Function to check if the linked list is palindrome or not
Node* slow= head; // Temp pointer
stack <int> s; // Declare a stack
// Push all elements of the list to the stack
while(slow != NULL){
s.push(slow->data);
slow = slow->ptr; // Move ahead
}
while(head != NULL ){ // Iterate in the list again and check by popping from the stack
int i=s.top(); // Get the top most element
s.pop(); // Pop the element
if(head -> data != i){ // Check if data is not same as popped element
return false;
}
head=head->ptr; // Move ahead
}
return true;
}


int main(){

// Addition of linked list
Node one = Node(1);
Node two = Node(2);
Node three = Node(3);
Node four = Node(2);
Node five = Node(1);

// Initialize the next pointer of every current pointer
five.ptr = NULL;
one.ptr = &two;
two.ptr = &three;
three.ptr = &four;
four.ptr = &five;
Node* temp = &one;


// Call function to check palindrome or not
int result = isPalindrome(&one);

if(result == 1)
cout<<"isPalindrome is true\n";
else
cout<<"isPalindrome is true\n";

return 0;
}