0%

LeetCode-234

LeetCode-234 回文链表

题目

结果

代码

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
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode p = head;
int length = 0;
while (p != null) {
length++;
p = p.next;
}
List<Integer> l1 = new LinkedList<>();
List<Integer> l2 = new LinkedList<>();
for (int i = 0; i < length / 2; i++) {
l1.add(head.val);
head = head.next;
}
// 如果长度是奇数
if (length % 2 != 0) {
head = head.next;
}
for (int i = 0; i < length / 2; i++) {
l2.add(head.val);
head = head.next;
}
Collections.reverse(l2);
return l1.equals(l2);
}
}

复杂度

时间复杂度:O(n)

空间复杂度:O(n)