leetcode twopoiner 234 palindrome linked list

THE

problem

Insert picture description here

solution

Code


/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode() : val(0), next(nullptr) {}
*     ListNode(int x) : val(x), next(nullptr) {}
*     ListNode(int x, ListNode *next) : val(x), next(next) {}
* };





思路: 看到链表问题, 就要想到左右指针, 快慢指针。 这里使用部分翻转加快慢指针。  查了一下答案思路是完全正确的。 看来自己技术进步了一些。 但是实施的细节还是不熟悉。

-  define  fast , slow 
-  loop fast into end , slow into mid;
-  
- - 
- 
*/

class Solution {
    
    
public:
   bool isPalindrome(ListNode* head) {
    
    

       if(!head || !head->next)
           return 1;
       ListNode* slow = head;
       ListNode* fast  = head;
       ListNode* p , *pre =NULL;
       while(fast&&fast->next){
    
    
           p = slow;
           slow = slow->next;
           fast = fast->next->next;
           p->next = pre;  // reverse
           pre = p;
       }
       if(fast){
    
    
           slow = slow->next;  // make  odd number pass
       }
       while(p){
    
    
           if(p->val != slow->val){
    
    
               return false;
           }
           else {
    
    
               p = p->next;
               slow = slow->next;
           }
       }
       return true;
       

   }
};

Summary and reflection

  1. Pay attention to consideration of boundary issues.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114166756