-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathSolution.java
47 lines (46 loc) · 1.06 KB
/
Solution.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head==null||head.next==null) {
return true;
}
ListNode slow=head;
ListNode fast=head;
while (fast!=null&&fast.next!=null) {
slow=slow.next;
fast=fast.next.next;
}
ListNode test=f(slow);
while (test!=null) {
if (test.val!=head.val) {
return false;
}
test=test.next;
head=head.next;
}
return true;
}
//原地翻转链表
public ListNode f(ListNode node){
if (node==null||node.next==null) {
return node;
}
ListNode l=node.next;
ListNode h;
node.next=null;
while (l!=null) {
h=l.next;
l.next=node;
node=l;
l=h;
}
return node;
}
}