-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCheckPalindrome.java
56 lines (49 loc) · 1.69 KB
/
CheckPalindrome.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
/*https://practice.geeksforgeeks.org/problems/check-if-linked-list-is-pallindrome/1*/
class Solution
{
//Function to check whether the list is palindrome.
boolean isPalindrome(Node head)
{
//if single node, return true
if (head.next == null) return true;
//find the break point and break the lists into two separate lists
//a modified two pointer approach
Node first = head;
Node second = head;
while (second.next != null)
{
second = second.next;
if (second.next == null) break;
first = first.next;
second = second.next;
}
second = first.next;
first.next = null;
//if second list has only one node and it is equal to the first node of first list, return true
if (second.next == null && head.data == second.data)
return true;
//reverse any one of the lists, here second list is reversed
Node prev = second, curr = second, newList = second.next;
while (newList != null)
{
curr = newList;
newList = newList.next;
curr.next = prev;
prev = curr;
}
second.next = null;
second = curr;
/*head contains the first list and second contains the second list*/
//till second list is exhausted
while (second != null)
{
//if the values are different at some point, return false
if (head.data != second.data)
return false;
head = head.next;
second = second.next;
}
//if not interrupted, return true
return true;
}
}