-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathPalindrome_LC.java
More file actions
83 lines (74 loc) · 2.36 KB
/
Palindrome_LC.java
File metadata and controls
83 lines (74 loc) · 2.36 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* 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; }
* }
*/
https://leetcode.com/problems/palindrome-linked-list
class Solution {
private ListNode reverse(ListNode currentNode, ListNode prevNode){
if(currentNode == null){
return prevNode; // Last Node (Become Start/ Head)
}
ListNode ahead = currentNode.next;
currentNode.next = prevNode;
return reverse(ahead, currentNode );
}
private boolean compare(ListNode firstHalf, ListNode secondHalf){
while(firstHalf!=null && secondHalf!=null){
if(firstHalf.val == secondHalf.val){
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
else{
return false;
}
}
return true;
}
public boolean isPalindrome(ListNode head) {
// Mid Node
// Reverse 2nd Half of the LL
// Split Compare 2 List
// Reverse 2nd Half (Org List)
// Step - 1 Mid Node Find out
// List Contains One Node
if(head.next == null){
return true;
}
ListNode slow , fast;
ListNode midNode = null;
ListNode prevNode = null;
slow = fast = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
prevNode = slow;
slow = slow.next;
}
// Odd Length List
if(fast!=null){
midNode = slow; // Place at Mid
slow = slow.next; // Mid + 1 (Move to next)
}
// Create SecondHalf of the List
ListNode secondHalf = slow;
// Create the First Half Here
prevNode.next = null;
// reverse the Second Half
secondHalf = reverse(secondHalf, null);
// Compare the First Half with the Second Half
boolean result = compare(head, secondHalf);
// Undo the Reverse
secondHalf = reverse(secondHalf, null);
// Recreate the Org List
if(midNode!=null){
prevNode.next = midNode;
midNode.next = secondHalf;
}
return result;
}
}