jayati

optimised linked ist palindrome question

Oct 11th, 2023
988
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <iostream>
  5. #include <stack>
  6. using namespace std;
  7. /* Link list Node */
  8. struct Node {
  9.   int data;
  10.   struct Node *next;
  11.   Node(int x) {
  12.     data = x;
  13.     next = NULL;
  14.   }
  15. };
  16.  
  17.  
  18.  
  19.  
  20. // } Driver Code Ends
  21. /*
  22. struct Node {
  23.   int data;
  24.   struct Node *next;
  25.   Node(int x) {
  26.     data = x;
  27.     next = NULL;
  28.   }
  29. };
  30. */
  31.  
  32. class Solution{
  33.   public:
  34.     //Function to check whether the list is palindrome.
  35.   bool isPalindrome(Node *head)
  36.     {
  37.         Node* fast=head;
  38.         Node* slow=head;
  39.        
  40.         //finding mid point
  41.         while(fast and fast->next){
  42.          
  43.             slow=slow->next;
  44.             fast=fast->next->next;
  45.         }
  46.        
  47.         //checking odd
  48.         if(fast!=NULL){
  49.             slow=slow->next;
  50.         }
  51.        
  52.         //reversing 2nd half
  53.         Node* curr=slow;
  54.         Node* prev=NULL;
  55.         Node* next=NULL;
  56.        
  57.         while(curr){
  58.             next=curr->next;
  59.             curr->next=prev;
  60.             prev=curr;
  61.             curr=next;
  62.         }
  63.        
  64.         slow=prev;//head of reversed 2nd half
  65.        
  66.         while(slow and head){
  67.             if(slow->data != head->data) return false;
  68.             slow=slow->next;
  69.             head=head->next;
  70.         }
  71.        
  72.         return true;
  73.     }
  74. };
  75.  
  76.  
  77. //{ Driver Code Starts.
  78. /* Driver program to test above function*/
  79. int main()
  80. {
  81.   int T,i,n,l,firstdata;
  82.     cin>>T;
  83.     while(T--)
  84.     {
  85.        
  86.         struct Node *head = NULL,  *tail = NULL;
  87.         cin>>n;
  88.         // taking first data of LL
  89.         cin>>firstdata;
  90.         head = new Node(firstdata);
  91.         tail = head;
  92.         // taking remaining data of LL
  93.         for(i=1;i<n;i++)
  94.         {
  95.             cin>>l;
  96.             tail->next = new Node(l);
  97.             tail = tail->next;
  98.         }
  99.     Solution obj;
  100.     cout<<obj.isPalindrome(head)<<endl;
  101.     }
  102.     return 0;
  103. }
  104.  
  105.  
  106. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment