Description:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
- Could you do it in O(n) time and O(1) space?
题意:判断一个链表是否为回文链表;
解法:判断回文,我们需要找出左右两个部分的链表;因此,第一步需要先计算出链表的长度后,找到右半部分的链表;第二步,将右半部分的链表逆序;第三步,从左半部分和右半部分同时开始遍历,判断是否为回文;
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode p = head;
int len = 0;
while (p != null) {
len++;
p = p.next;
}
p = head;
ListNode right = head;
for (int i = 0; i < (len+1)/2-1; i++) {
p = p.next;
right = right.next;
}
right = right.next;
p.next = null;
p = null;
while (right != null) {
ListNode temp = right.next;
right.next = p;
p = right;
right = temp;
}
right = p;
ListNode left = head;
while (left != null && right != null) {
if (left.val != right.val) {
return false;
}
left = left.next;
right = right.next;
}
return true;
}
}