目录
题目
Given a singly linked list, determine if it is a palindrome.
解决方案
1 | /** |
注意事项
- 一共遍历了两遍,第一遍把所有值存起来;第二遍将存起来的值倒序和链表中每个值比较。
- 该方法效率较低,更好的方法如下:
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
27public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) slow = slow.next;
slow = reverse(slow);
while(slow != null && head.val == slow.val) {
head = head.next;
slow = slow.next;
}
return slow == null;
}
private ListNode reverse(ListNode head) {
ListNode prev = null;
while(head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
该方法中包含了很常用的链表翻转方法:1
2
3
4
5
6
7
8
9
10private ListNode reverse(ListNode head) {
ListNode prev = null;
while(head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}