knakul853

Untitled

Jun 17th, 2020
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     bool isPalindrome(ListNode* head) {
  7.        
  8.         ListNode* slow = head;
  9.         ListNode* fast = head;
  10.        
  11.         while( fast && fast->next )
  12.         {
  13.             fast = fast->next->next;
  14.             slow = slow->next;
  15.         }
  16.        
  17.         slow = reverse( slow );
  18.         fast =  head;
  19.        
  20.         while( slow && fast )
  21.         {
  22.             if(slow->val != fast->val )return false;
  23.            
  24.             slow = slow->next;
  25.             fast = fast->next;
  26.         }
  27.        
  28.         return true;
  29.        
  30.        
  31.     }
  32.    
  33.     ListNode* reverse( ListNode* head )
  34.     {
  35.         ListNode* pre = NULL;
  36.        
  37.         while( head )
  38.         {
  39.             //1->2->3
  40.              ListNode* temp = head->next;
  41.             head->next = pre;
  42.             pre = head;
  43.             head = temp;
  44.         }
  45.        
  46.         return pre;
  47.     }
  48. };
Add Comment
Please, Sign In to add comment