File tree Expand file tree Collapse file tree 1 file changed +41
-1
lines changed
234-palindrome-linked-list Expand file tree Collapse file tree 1 file changed +41
-1
lines changed Original file line number Diff line number Diff line change 9
9
* }
10
10
*/
11
11
class Solution {
12
- public boolean isPalindrome (ListNode head ) {
12
+
13
+ public static ListNode recursiveReverse (ListNode head ){
14
+ if (head == null || head .next == null ){return head ;}
15
+
16
+ ListNode new_head = recursiveReverse (head .next );
17
+ head .next .next = head ;
18
+ head .next = null ;
19
+
20
+ return new_head ;
21
+ }
22
+
23
+ public ListNode findMiddle (ListNode head ){
24
+ ListNode slow = head ;
25
+ ListNode fast = head ;
26
+
27
+ while (fast .next != null && fast .next .next != null ){
28
+ slow = slow .next ;
29
+ fast = fast .next .next ;
30
+ }
31
+ return slow ;
32
+ }
33
+
34
+ public boolean isPalidrome2 (ListNode head ){
13
35
ArrayList <Integer > list = new ArrayList <Integer >();
14
36
ListNode temp = head ;
15
37
@@ -29,4 +51,22 @@ public boolean isPalindrome(ListNode head) {
29
51
}
30
52
return true ;
31
53
}
54
+ public boolean isPalindrome (ListNode head ) {
55
+ if (head == null || head .next == null ){return true ;}
56
+
57
+ ListNode middle = findMiddle (head );
58
+ ListNode revHead = recursiveReverse (middle .next );
59
+
60
+ ListNode firstHead = head ;
61
+
62
+ while (revHead != null ){
63
+ if (firstHead .val != revHead .val ){
64
+ return false ;
65
+ }
66
+ firstHead = firstHead .next ;
67
+ revHead = revHead .next ;
68
+ }
69
+ return true ;
70
+
71
+ }
32
72
}
You can’t perform that action at this time.
0 commit comments