1.题目
链表的回文结构:
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
回文链表
2.分析
创建两个引用,找到中间结点。最好从中间位置向后反转,然后判断回文
奇数个结点:
1.
7.
扫描二维码关注公众号,回复:
13322458 查看本文章
偶数个结点:
1.
3.
3.代码
//判断回文
public boolean chkPalindrome(ListNode head) {
// write code here
if (head == null) return true;
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//slow走到了中间位置
//反转
ListNode cur = slow.next;
while (cur != null) {
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//反完成
while (head != slow) {
if (head.val != slow.val) {
return false;
}
if (head.next == slow) {
//偶数个情况
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
测试:
idea测试将方法参数去掉,用自己的head,力扣上面要加参数
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addLast(11);
myLinkedList.addLast(23);
myLinkedList.addLast(20);
myLinkedList.addLast(23);
myLinkedList.addLast(145);
System.out.println("myLinkedList:");
myLinkedList.display();
boolean ret=myLinkedList.chkPalindrome();
System.out.println(ret);
}
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addLast(11);
myLinkedList.addLast(23);
myLinkedList.addLast(20);
myLinkedList.addLast(23);
myLinkedList.addLast(11);
System.out.println("myLinkedList:");
myLinkedList.display();
boolean ret=myLinkedList.chkPalindrome();
System.out.println(ret);
}