参考自http://blog.youkuaiyun.com/xudli/article/details/46871949
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
[思路]
先分成大小相同(可能长度差1) 两部分, reverse一个list. 再比较.
[CODE]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.math.*;
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode middle = partition(head);
middle = reverseList(middle);
while( head != null && middle != null ){
if(head.val != middle.val){
return false;
}
else{
head = head.next;
middle = middle.next;
}
}
return true;
}
public ListNode partition(ListNode head){
ListNode p = head;
while(p.next != null && p.next.next != null){
head = head.next;
p = p.next.next;
}
p = head.next;
head.next = null;
return p;
}
public ListNode reverseList(ListNode head){
if(head == null || head.next == null) return head;
ListNode pre = head;
ListNode p = head.next;
ListNode nxt = null;
pre.next = null;
while(p != null){
nxt = p.next;
p.next = pre;
pre = p;
p = nxt;
}
return pre;
}
}
代码分析:
1、partition函数:函数中用了两个指针,一个每次走一步,另外一个每次走两步。保证在二分之一处(加一)处分开链表。注意在函数返回之前断开两段链表的指针。
2、reverseList函数:选中链表中的某个点,记录它的pre节点和下一个节点,然后改变它的指针指向,指向前一个节点。注意初始值的赋值。
pre.next = null;
将第一个点的指向先断开。