-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path234-palindromeLinkedList.java
More file actions
42 lines (41 loc) · 1.12 KB
/
234-palindromeLinkedList.java
File metadata and controls
42 lines (41 loc) · 1.12 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
// 后半部分反转,从外围开始比较
class Solution_234 {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode first = head;
ListNode last = head;
while(last.next!=null && last.next.next!=null) {
first = first.next;
last = last.next.next;
}
first = reverse(first);
while(first!=null && head != null) {
// System.out.println(first.val);
// System.out.println(head.val);
if(first.val!=head.val) return false;
first = first.next;
head = head.next;
}
return true;
}
public ListNode reverse(ListNode mid) {
ListNode pre = null;
ListNode tmp = mid;
while(mid.next != null) {
tmp = mid.next;
mid.next = pre;
pre = mid;
mid = tmp;
}
mid.next = pre;
return mid;
}
}