forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindromeLinkedList.java
78 lines (61 loc) · 1.56 KB
/
PalindromeLinkedList.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
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* 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; }
* }
*/
class Solution {
// TC : O(n)
// SC : O(1)
public boolean isPalindrome(ListNode head) {
if(head==null || head.next==null){
return true;
}
ListNode slow =head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
fast=fast.next;
if(fast!=null){
fast = fast.next;
}
slow = slow.next;
}
// F
// 1 2 3 2 1
// S
// F
// 1 2 2 1
// S S
if(fast!=null){
slow = slow.next;
}
ListNode head2 = reverse(slow);
ListNode head1 = head;
while(head1!=null && head2!=null){
if(head1.val !=head2.val){
return false;
}
head1 = head1.next;
head2 = head2.next;
}
return true;
}
private ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode curr = head;
ListNode prev = null;
while(curr!=null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}