forked from yunyinl/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.java
More file actions
53 lines (47 loc) · 1.29 KB
/
Copy pathPalindromeLinkedList.java
File metadata and controls
53 lines (47 loc) · 1.29 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
52
53
package amazon;
import entity.ListNode;
/**
* https://leetcode.com/problems/palindrome-linked-list/
* 判断链表是不是回文
* 做法,快慢指针就可以了。
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Created by anduo on 17-3-13.
*/
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode slow = head, fast = head.next;
// 找到中间的节点
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) {// 奇数的情况
slow = slow.next;
}
// 翻转后边的节点
ListNode reverse = reverse(slow);
while (head != null && reverse != null && head.val == reverse.val) {
head = head.next;
reverse = reverse.next;
}
return reverse == null;
}
private ListNode reverse(ListNode head) {
ListNode now = null;
while (head != null) {
ListNode next = head.next;
head.next = now;
now = head;
head = next;
}
return now;
}
}