-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
51 lines (43 loc) · 1.22 KB
/
PalindromeLinkedList.java
File metadata and controls
51 lines (43 loc) · 1.22 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
package linkedlist;
import linkedlist.LinkedListTest.ListNode;
/**
* @author Shogo Akiyama
* Solved on 12/04/2019
*
* 234. Palindrome Linked List
* https://leetcode.com/problems/palindrome-linked-list/
* Difficulty: Easy
*
* Approach: Recursion
* Runtime: 1 ms, faster than 99.47% of Java online submissions for Palindrome Linked List.
* Memory Usage: 44.3 MB, less than 6.10% of Java online submissions for Palindrome Linked List.
*
* Time Complexity: O(n)
* Space Complexity: O(n) for recursive stack, O(1) without counting recursive stack
* Where n is the numbers of a linked list
*
* @see LinkedListTest#testPalindromeLinkedList()
*/
public class PalindromeLinkedList {
private ListNode top;
private boolean retVal;
public boolean isPalindrome(ListNode head) {
if(head == null){
return true;
}
top = head;
return check(head);
}
private boolean check(ListNode node){
if(node.next == null){
return top.val == node.val;
}
retVal = check(node.next);
if(retVal){
top = top.next;
return top.val == node.val;
}else{
return false;
}
}
}