-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234. Palindrome Linked List
77 lines (73 loc) · 2.07 KB
/
234. Palindrome Linked List
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null)
return true;
ListNode fast=head;
ListNode low=head;
ListNode pre=null;
ListNode cur=head;
while(fast.next!=null&&fast.next.next!=null){
ListNode next=cur.next;
fast=fast.next.next;
low=low.next;
cur.next=pre;
pre=cur;
cur=next;
}
if(fast.next==null){
cur=cur.next;
}
else{ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
while(cur!=null){
if(cur.val!=pre.val)
return false;
cur=cur.next;
pre=pre.next;
}
return true;
}
}
//更简洁的方法
/**
* 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 fast=head;
ListNode low=head;
ListNode pre=null;
ListNode cur=head;
while(fast!=null&&fast.next!=null){// you should be careful about that fast!=null must be in front of the statement fast.next!=null
//Or there may be a nullpointer exception
ListNode next=cur.next;
fast=fast.next.next;
low=low.next;
cur.next=pre;
pre=cur;
cur=next;
}
if(fast!=null){ //you cannot use fast.next==null Or there may be a null pointer exception.
//Actually if you use while(a!=null&&a.next!=null) in the following you cannot use a.next. you can only use a, Or there may be
a null pointer exception.
cur=cur.next;
}
while(cur!=null){
if(cur.val!=pre.val)
return false;
cur=cur.next;
pre=pre.next;
}
return true;
}
}