Java [Leetcode 234]Palindrome Linked List

时间:2023-01-02 04:11:16

题目描述:

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?

解题思路:

使用O(n)的时间复杂度及O(1)的时间复杂度表明顺序遍历链表以及不能够开辟跟链表相当的空间,这样可以找出中间的位置,然后将后半部分的链表反转,然后跟前半部分的链表逐个位置比对。

代码如下:

/**
* 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) {
ListNode end = head;
ListNode mid = head;
while(end != null && end.next != null){
end = end.next.next;
mid = mid.next;
}
if(end != null) //in case of odd list
mid = mid.next;
mid = reverseList(mid);
while(mid != null){
if(mid.val != head.val)
return false;
mid = mid.next;
head = head.next;
}
return true;
} public ListNode reverseList(ListNode head){
ListNode pre = null, next = null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}