-
Notifications
You must be signed in to change notification settings - Fork 0
/
CheckListPalindrome.java
65 lines (53 loc) · 1.65 KB
/
CheckListPalindrome.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.* ;
import java.io.*;
/****************************************************************
Following is the class structure of the LinkedListNode class:
class LinkedListNode<T> {
T data;
LinkedListNode<T> next;
public LinkedListNode(T data) {
this.data = data;
}
}
*****************************************************************/
public class Solution {
public static boolean isPalindrome(LinkedListNode<Integer> head) {
// Write your code here!
LinkedListNode fast=head,slow=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//if the ll size is odd
if(fast!=null){
slow=slow.next;
}
slow=reverseList(slow);//right half ll
fast=head;//left half ll
// compare two lls
while(slow!=null){
if(fast.get(val)!=slow.get(val))
return false;
fast=fast.next;
slow=slow.next;
}
return true;
}
public static LinkedListNode reverseList(LinkedListNode head) {
if(head==null || head.next==null){
return head;
}
LinkedListNode prevNode=head;
LinkedListNode currNode=head.next;
while(currNode!=null){
LinkedListNode nextNode=currNode.next;
currNode.next=prevNode;//does the reversing part
//update
prevNode=currNode;
currNode=nextNode;
}
head.next=null;
head=prevNode;
return head;
}
}