234. Palindrome Linked List

LeetCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* 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;
}
}

0%