原题链接在这里:https://leetcode.com/problems/palindrome-linked-list/
思路: 原题要求time O(n), space O(1). 所以不能用额外空间。先找到中点,reverse中点后面的list部分,再与head开始逐个比较 val. 期中reverse部分可以参见Reverse Linked List中的Method 2.
AC Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
ListNode walker = head;
ListNode runner = head;
while(runner.next != null && runner.next.next != null){
runner = runner.next.next;
walker = walker.next;
}
ListNode middleHead = walker.next;
middleHead = reverseList(middleHead);
while(head != null && middleHead != null){
if(head.val != middleHead.val){
return false;
}
head = head.next;
middleHead = middleHead.next;
}
return true;
}
private ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode tail = head;
ListNode cur = head;
ListNode pre;
ListNode temp;
while(tail.next!=null){
pre = cur;
cur = tail.next;
temp = cur.next;
cur.next = pre;
tail.next = temp;
}
return cur;
}
}

本文介绍了一种在时间和空间复杂度限定下判断链表是否为回文的有效算法。该方法首先找到链表的中点,反转后半部分链表,并从前半部分与反转后的后半部分进行对比。
498

被折叠的 条评论
为什么被折叠?



