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?
判断一个链表是不是回文
以下算法超时
/**
* 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;
int n=1;
ListNode head1=head;
// ListNode head2=head;
while(head1.next!=null)
{
head1=head1.next;
n++;
}
for(int i=0;i<n/2;i++)
{
ListNode head2=head;//要在for循环内初始化,否则第一次循环没有问题,第二次循环时指针位置已经不是初始位置
ListNode head3=head;
int b=i;
while(b>0){
head2=head2.next;
b--;
}
int a=i;
while(n-a>1){
head3=head3.next;
a++;
}
if(head3.val!=head2.val)
return false;
}
return true;
}
}
先找到链表的中间位置(考虑奇数个节点和偶数个节点两种情况),将后半部分逆序(头插法)然后判断是否相等‘
public class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
if(fast!=null) slow=slow.next;
slow=reverse(slow);
while(slow!=null&&slow.val==head.val){
slow=slow.next;
head=head.next;
}
return slow==null;
}
public ListNode reverse(ListNode head){
ListNode prev=null;
while(head!=null){
ListNode next=head.next;
head.next=prev;
prev=head;
head=next;
}
return prev;
}
}
头插法:另构造一个链表,不断向前加节点