题目描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
解题思路
回文链表就是从中间看,链表是对称的,那么我们只需将后半段链表反转,逐个判断相等即可
代码如下
import java.util.*;
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class PalindromeList {
public boolean chkPalindrome(ListNode A) {
// write code here
if(A == null)return false;
if(A.next == null)return true;
//查找中间节点
ListNode fast = A;
ListNode slow = A;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
//后半链表反转
ListNode h = slow.next;
ListNode cur = h.next;
ListNode curNext = cur.next;
slow.next = null;
h.next = null;
while(cur != fast){
cur.next = h;
h = cur;
cur = curNext;
if(cur != null){
curNext = cur.next;
}
}
//比较
slow = A;
cur = h;
while(cur != null){
if(slow.val != cur.val){
return false;
}
slow = slow.next;
cur = cur.next;
}
return true;
}
}