难度:简单
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false示例 2:
输入: 1->2->2->1 输出: true进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
分析:
①用快慢指针找到中间节点
②反转后半截链表,然后前后半截链表比较元素大小
代码:
/**
* 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)
return true;
ListNode preHalf = findHalfPoint(head);
ListNode lastHalf = reverseList(preHalf.next);
//start to compare
boolean res = true;
ListNode p1 = head,p2 = lastHalf;
while (res && p2 != null){
if(p1.val != p2.val)
res = false;
p1 = p1.next;
p2 = p2.next;
}
return res;
}
private ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
private ListNode findHalfPoint(ListNode head) {
ListNode slow = head,fast = head;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
结果: