forked from fineanmol/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
51 lines (47 loc) · 1.6 KB
/
Copy pathPalindromeLinkedList.java
File metadata and controls
51 lines (47 loc) · 1.6 KB
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
/*You have been given a head to a singly linked list of integers. Write a function check to whether the list given is a 'Palindrome' or not.*/
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) {
//Your code goes here
if(head==null || head.next==null){
return true;
}
LinkedListNode<Integer> middle=findMiddle(head);
LinkedListNode<Integer> secondHalfStart=reverse(middle.next);
LinkedListNode<Integer> firstHalfStart=head;
while(secondHalfStart!=null){
if(firstHalfStart.data!=secondHalfStart.data){
return false;
}
firstHalfStart=firstHalfStart.next;
secondHalfStart=secondHalfStart.next;
}return true;
//Your code goes here
}
public static LinkedListNode<Integer> reverse(LinkedListNode<Integer> head){
LinkedListNode<Integer> prev=null;
LinkedListNode<Integer> cur=head;
LinkedListNode<Integer> next = null;
while(cur!=null){
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}return prev;
}
public static LinkedListNode<Integer> findMiddle(LinkedListNode<Integer> head){
LinkedListNode<Integer> fast=head;
LinkedListNode<Integer> slow=head;
while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}