Steps:
1. break list in 2 parts
2. reverse second list
3. compare list
void checkLinkedListpalindrom(Node node) {
Node p = node;
Node q = node;
Node start = node;
Node secondstart=null;
while(true) {
p = p.next.next;
if(p==null) {
secondstart = q.next;
q.next = null;
break;
}
if(p.next==null) {
secondstart = q.next.next;
q.next = null;
break;
}
q = q.next;
}
secondstart = reverse(secondstart);
System.out.println(compareList(start, secondstart));
}
boolean compareList(Node n1, Node n2) {
boolean flag = true;
while(null!=n1 || null!=n2) {
if(n1.value==n2.value) {
n1 = n1.next;
n2 = n2.next;
}else {
flag = false;
break;
}
}
return flag;
}
Node reverse(Node node) {
Node pre = null;
Node current =node;
while(null!=current) {
Node temp = current.next;
current.next = pre;
pre = current;
current = temp;
}
return pre;
}
No comments:
Post a Comment