Recursion Function(재귀함수) : 자기 자신을 재참조, 종료 조건으로 종료 시점을 제어한다.
leetcode : 234. Palindrome Linked List
- 조건
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
private ListNode current;
public boolean isPalindrome(ListNode head) {
current = head;
return isPalindromeHelper(head);
}
public boolean isPalindromeHelper(ListNode node) {
if (node == null) {
return true;
}
boolean isPalindromeTail = isPalindromeHelper(node.next);
boolean isPalindromeCurrent = (current.val == node.val);
current = current.next;
return isPalindromeTail && isPalindromeCurrent;
}
}