编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
O(n) 时间复杂度和 O(1) 空间复杂度解法:
先找到中间点,把后半部分反转,然后开始比较前后两段是否相等。
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
int count = 0;
ListNode node = head;
while(node != null) {
node = node.next;
count++;
}
int i = 0;
node = head;
ListNode pre = node;
int mid = (count)/2;
while(i < mid) {
i++;
pre = node;
node = node.next;
}
if(count %2 ==1) {
node = node.next;
}
pre.next = null;
// 反转后半段
ListNode node_pre = node;
ListNode node_pre_pre = null;
while(node != null && node.next != null) {
node_pre = node;
node = node.next;
node_pre.next = node_pre_pre;
node_pre_pre = node_pre;
if(node.next == null) {
node.next = node_pre;
break;
}
}
// node.next = node_pre;
ListNode head_node = head;
// 比较前后两部分是否相等
while(head_node != null) {
if(head_node.val != node.val ) {
return false;
}
head_node = head_node.next;
node = node.next;
}
return true;
}
}