Advertisement
Kali_prasad

check the palindromic list or not

Apr 28th, 2022
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     bool isPalindrome(ListNode* head) {
  14.         ListNode* A=head;
  15.          if(!A||!A->next) return true;
  16.         ListNode* slow=A;
  17.     ListNode* fast=A;
  18.     ListNode* back=NULL;
  19.     ListNode* front=A->next;
  20.     while(fast->next!=NULL&&fast->next->next!=NULL)
  21.     {  
  22.         fast=fast->next->next;
  23.         back=slow;
  24.         slow=front;
  25.         front=front->next;
  26.         slow->next=back;
  27.        
  28.     }
  29.      ListNode* left=NULL;
  30.      ListNode* right=NULL;
  31.     if(fast->next==NULL)
  32.     {
  33.         left=slow->next;
  34.         right=front;
  35.     }
  36.     else
  37.     {
  38.         left=slow;
  39.         right=front;
  40.     }
  41.     while(left!=NULL&&right!=NULL)
  42.     {
  43.         if(left->val!=right->val) return false;
  44.         left=left->next;
  45.         right=right->next;
  46.     }
  47.     return true;
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement