题目链接:
题目描述:
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
题目分析:
1.找中间节点
2.翻转后半部分
cur:当前需要翻转的结点 cur = slow.next
slow:cur的前驱
curNext:cur的后继结点
while(cur != null){
curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
3.head指向左边头结点,向右走,slow指向右边尾结点,向左走,走的过程当中,一旦出现head.val != slow.val
就 return false
运行代码:
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) {
if(A == null){
return false;
}
// write code here
ListNode fast = A;
ListNode slow = A;
ListNode head = A;
ListNode cur = null;
ListNode curNext = null;
while(fast!=null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
cur = slow.next;
while(cur!=null){
curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
while(head != slow){
if(head.val != slow.val){
return false;
}
//偶数个结点的情况下,这段代码必须在判断完val相同之后执行
if(head.next == slow){
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
}