My functional solution


  • 0
    2
        /**
         * Definition for singly-linked list.
         * public class ListNode {
         *     int val;
         *     ListNode next;
         *     ListNode(int x) { val = x; }
         * }
         */`enter code here`
        
     class Solution {
        public:
            ListNode * getSecondPart(ListNode* head) {
                if(!head) return 0;
                ListNode* fast=head, * slow=head;
                while(fast && fast->next) {
                    fast=fast->next->next;
                    slow=slow->next;
                }
                return slow;
            }
            
            ListNode * reverseList(ListNode* head) {
                ListNode* ret=0;
                while(head) {
                    ListNode* temp=head->next;
                    head->next=ret;
                    ret=head;
                    head=temp;
                }
                return ret;
            }
        
            bool sameList(ListNode* la, ListNode* lb) {
                while(la && lb) {
                    if(la->val!=lb->val) return false;
                    la=la->next;
                    lb=lb->next;
                }
                if(!la && !lb) return true;
                if(!lb && la && !la->next) return true;
                return false;
            }
        
            bool isPalindrome(ListNode* head) {
                ListNode* first=head, * second=getSecondPart(head);
                second=reverseList(second);
                return sameList(first, second);
            }
        };

  • 0
    Z
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.