请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:输入: 1->2->2->1 输出: true 进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一反应是快慢指针找出中间位置然后判断前后是否相同。后来意识到判断回文…所以还需要反转后一半链表…虽然有点耍赖但是好歹完成了要求的O(1)空间:
class Solution {
ListNode reverse(ListNode head) {
ListNode next = head.next;
head.next = null;
while(next != null) {
ListNode t = next.next;
next.next = head;
head = next;
next = t;
}
return head;
}
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null)
return true;
//快慢指针呗
ListNode fast = head, slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if(fast != null)
slow = slow.next;
slow = reverse(slow);
while(slow != null) {
if(head.val != slow.val)
return false;
head = head.next;
slow = slow.next;
}
return true;
}
}
题解中有个递归的解法很酷,相当于在栈中维护了一个栈(感觉哪里不对)。不过多做了一半额外的工作,实现并优化一下:
class Solution {
ListNode front;
boolean rec(ListNode head) {
if(head == null)
return true;
if(!rec(head.next))
return false;
if(front != null && head.val != front.val)
return false;
if(front == null)
return true;
if(front == head || front.next == head) {
front = null;
} else {
front = front.next;
}
return true;
}
public boolean isPalindrome(ListNode head) {
front = head;
return rec(head);
}
}
比快慢指针慢
耍赖大法好