Skip to content

Commit b425938

Browse files
committed
Time: 9 ms (25.67%) | Memory: 71.5 MB (5.66%) - LeetSync
1 parent 2491668 commit b425938

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

234-palindrome-linked-list/palindrome-linked-list.java

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,29 @@
99
* }
1010
*/
1111
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){
1335
ArrayList<Integer> list = new ArrayList<Integer>();
1436
ListNode temp = head;
1537

@@ -29,4 +51,22 @@ public boolean isPalindrome(ListNode head) {
2951
}
3052
return true;
3153
}
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+
}
3272
}

0 commit comments

Comments
 (0)