C# Solution


  • 0
    public class Solution {
        public bool IsPalindrome(ListNode head) {
            if (head == null || head.next == null)
                return true;
                
            ListNode slow = head, 
                     fast = head, 
                     rightHalfHead = null;
            
            while (fast.next != null && fast.next.next != null)
            {
                fast = fast.next.next;
                slow = slow.next;
            }
            
            rightHalfHead = Reverse(slow.next);
            slow.next = null;
            
            while (rightHalfHead != null)
            {
                if (head.val != rightHalfHead.val)
                    return false;
                
                head = head.next;
                rightHalfHead = rightHalfHead.next;
            }
            
            return true;
        }
        
        private ListNode Reverse(ListNode head)
        {
            ListNode node1 = null, 
                     node2 = head, 
                     node3 = null;
                     
            if (node2 != null)
                node3 = node2.next;
            
            while (node2 != null)
            {
                node2.next = node1;
                
                node1 = node2;
                node2 = node3;
                
                if (node2 != null)
                    node3 = node2.next;
            }
            
            return node1;
        }
    }

Log in to reply
 

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