题目
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?
分析
1 题目要求 time O(n) space O(1), 意味着要在原链表操作
2 对于链表的回文串的判断,只能通过翻转 然后两个链表再从头到尾的进行比较
翻转一开始想到的是翻转整个链表,但是这样操作后这个链表就变了,什么意思,就是翻转之后得到的链表,好,ok, 还是完整的,但是再比较新的head 时,这时候的head 已经不是之前的head了 head.next = null.
所以,翻转只能翻转一半
1 快慢指针 确定位于中间位置的结点
2 翻转链表,将中间位置的结点作为头结点传入翻转的函数中,这里要会怎么翻转一个链表
3 循环比较 head 和 newslow的两个链表即可
代码
public ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fastNode = dummy;
ListNode slowNode = dummy;
while (fastNode != null && fastNode.next != null){
fastNode = fastNode.next.next;
slowNode = slowNode.next;
}
slowNode = reverse(slowNode);
while (head != null && slowNode != null){
if(head.val != slowNode.val){
return false;
}
head = head.next;
slowNode = slowNode.next;
}
return true;
}