Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- #include <stack>
- using namespace std;
- /* Link list Node */
- struct Node {
- int data;
- struct Node *next;
- Node(int x) {
- data = x;
- next = NULL;
- }
- };
- // } Driver Code Ends
- /*
- struct Node {
- int data;
- struct Node *next;
- Node(int x) {
- data = x;
- next = NULL;
- }
- };
- */
- class Solution{
- public:
- //Function to check whether the list is palindrome.
- Node* reverseLinkedList(Node* head) {
- Node* prev = NULL;
- Node* current = head;
- Node* nextNode;
- while (current != NULL) {
- nextNode = current->next;
- current->next = prev;
- prev = current;
- current = nextNode;
- }
- return prev;
- }
- // Function to copy a linked list
- Node* copyLinkedList(Node* head) {
- if (head == NULL) return NULL;
- Node* nHead = new Node(head->data);
- Node* current = nHead;
- Node* original = head->next;
- while (original != NULL) {
- current->next = new Node(original->data);
- current = current->next;
- original = original->next;
- }
- return nHead;
- }
- bool isPalindrome(Node *head)
- {
- //Your code here
- Node* nhead = copyLinkedList(head);
- Node* newHead = reverseLinkedList(head);
- Node* temp=newHead;
- Node* temp2=nhead;
- bool f=true;
- while(temp!=NULL && temp2!=NULL)
- {
- // cout<<temp->data<<" "<<temp2->data<<endl;
- if(temp->data!=temp2->data)
- {
- f=false;
- break;
- }
- temp=temp->next;
- temp2=temp2->next;
- }
- if(f)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- };
- //{ Driver Code Starts.
- /* Driver program to test above function*/
- int main()
- {
- int T,i,n,l,firstdata;
- cin>>T;
- while(T--)
- {
- struct Node *head = NULL, *tail = NULL;
- cin>>n;
- // taking first data of LL
- cin>>firstdata;
- head = new Node(firstdata);
- tail = head;
- // taking remaining data of LL
- for(i=1;i<n;i++)
- {
- cin>>l;
- tail->next = new Node(l);
- tail = tail->next;
- }
- Solution obj;
- cout<<obj.isPalindrome(head)<<endl;
- }
- return 0;
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment