234. Palindrome Linked List Posted on 2020-09-09 | Edited on 2021-01-22 LeetCode 12345678910111213141516171819202122232425262728293031323334353637383940414243/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */class Solution { private ListNode endOfFirstHalf(ListNode head){ ListNode fast=head,slow=fast; while(fast.next!=null&&fast.next.next!=null){ fast=fast.next.next; slow=slow.next; } return slow; } private ListNode reverseList(ListNode head){ ListNode prev=null,curr=head; while(curr!=null){ ListNode nextNode=curr.next; curr.next=prev; prev=curr; curr=nextNode; } return prev; } public boolean isPalindrome(ListNode head) { if(head==null||head.next==null) return true; ListNode endOfFirstHalfNode=endOfFirstHalf(head); ListNode reversedSecondHalf=reverseList(endOfFirstHalfNode.next); ListNode p1=head,p2=reversedSecondHalf; while(p2!=null&&p1.val==p2.val){ p1=p1.next; p2=p2.next; } return p2==null; }}