File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean isPalindrome(ListNode head) {
3
+ if(head == null || head.next == null) return true;
4
+ List<Integer> l = new ArrayList<>();
5
+ while(head != null){
6
+ l.add(head.val);
7
+ head = head.next;
8
+ }
9
+ int start = 0, end = l.size()-1;
10
+ while(start < end){
11
+ if(l.get(start) != l.get(end)) return false;
12
+ start++;end--;
13
+ }
14
+ return true;
15
+ }
16
+ }
17
+
18
+ class Solution {
19
+ public boolean isPalindrome(ListNode head) {
20
+ //Find Mid
21
+ ListNode fast = head;
22
+ ListNode slow = head;
23
+
24
+ while(fast.next != null && fast.next.next != null) {
25
+ slow = slow.next;
26
+ fast = fast.next.next;
27
+ }
28
+
29
+ // 1, ||| 2. |||| 3 --> slow = 2, fast = 3
30
+ if(fast != null) slow = slow.next;
31
+
32
+ //Reverse the list start from slow.
33
+ ListNode revHead = reverse(slow);
34
+
35
+ while(revHead != null) {
36
+ if(revHead.val != head.val) return false;
37
+ else {
38
+ revHead = revHead.next;
39
+ head = head.next;
40
+ }
41
+ }
42
+ return true;
43
+ }
44
+
45
+ public ListNode reverse(ListNode head) {
46
+ ListNode prev = null;
47
+ while(head != null) {
48
+ ListNode next = head.next;
49
+ head.next = prev;
50
+ prev = head;
51
+ head = next;
52
+ }
53
+ return prev;
54
+ }
55
+ }
You can’t perform that action at this time.
0 commit comments