-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPalindrome List.java
More file actions
92 lines (59 loc) · 1.71 KB
/
Palindrome List.java
File metadata and controls
92 lines (59 loc) · 1.71 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
84
85
86
87
88
89
90
91
92
//https://www.interviewbit.com/problems/palindrome-list/#
/**
* Definition for singly-linked list.
* class ListNode {
* public int val;
* public ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
public class Solution {
public int lPalin(ListNode A) {
ListNode p1 = A, p2 = A;
int N = 0;
while(p1 != null){
p1 = p1.next;
N++;
}
p1 = A;
if(N == 1) return 1;
if(N == 2){
p2 = p2.next;
if(p1.val == p2.val) return 1;
return 0;
}
p1 = A;
// N/2 is half
int mid = N/2 - 1;
for(int i = 1; i <= mid; i++)
p2 = p2.next;
if(N%2 == 0){
if(p2.val != p2.next.val) return 0;
}
p2 = p2.next;
ListNode saved = p2;
ListNode prev = p2;
ListNode head = p2.next;
//reverse from p2 onwards
while(head != null){
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
p2 = prev;
//check
int ans = 1;
while(true){
if(p1 == saved || p2 == saved || p1 == p2)
break;
if(p1.val != p2.val){
ans = 0;
break;
}
p1 = p1.next;
p2 = p2.next;
}
return ans;
}
}