/**
* 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 {
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
List<Integer> s = new ArrayList<Integer>();
int prev = head.val;
ListNode cur = head.next;
while (cur != null) {
s.add(cur.val);
cur = cur.next;
}
int size = s.size() - 1;
for (int i = 0; i < size / 2; i++) {
if (s.get(i) != s.get(size - i)) {
return false;
}
}
return true;
}
}
중간값 고려 x
/**
* 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 {
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
List<Integer> st = new ArrayList<Integer>();
ListNode cur = head;
while (cur != null) {
st.add(cur.val);
cur = cur.next;
}
int s = 0;
int e = st.size() - 1;
while (e > s) {
if (!st.get(s).equals(st.get(e))) {
return false;
}
e--;
s++;
}
return true;
}
}
Runtime: 3 ms, faster than 24.98% of Java online submissions for Palindrome Linked List.
Memory Usage: 43 MB, less than 23.25% of Java online submissions for Palindrome Linked List.
O(1)이 아닌데 귀찮아..