题目描述
链接:https://www.nowcoder.com/questionTerminal/d281619e4b3e4a60a2cc66ea32855bfa
来源:牛客网
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
解题思路:运用快慢指针
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;
}
if(A.next == null){
return true;
}
ListNode slow = A;
ListNode fast = A;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode cur = slow.next;
while(cur != null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
while(slow != A){
if(A.val != slow.val){
return false;
}
if(A.next == slow){//判断链表为偶数时
return true;
}
slow = slow.next;
A = A.next;
}
return true;
}
}