Advertisement
RaFiN_

reverse the 2nd half and check pallin linked list

Dec 25th, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode(int x) : val(x), next(NULL) {}
  7.  * };
  8.  */
  9. class Solution {
  10. public:
  11.     bool isPalindrome(ListNode* head) {
  12.         if(!head)return true;
  13.         ListNode *slow = head,*fast = head->next;
  14.         while(fast&&fast->next){
  15.             slow = slow->next;
  16.             fast = fast->next->next;
  17.         }
  18.         ListNode *prev = slow;
  19.         ListNode *pp = prev->next;
  20.         prev->next = NULL;
  21.         while(pp){
  22.             ListNode *tmp = pp->next;
  23.             pp->next = prev;
  24.             prev = pp;
  25.             pp = tmp;
  26.         }
  27.         while(head&&prev){
  28.             if(head->val!=prev->val)return false;
  29.             head = head->next;
  30.             prev = prev->next;
  31.         }
  32.         return true;
  33.        
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement