LeetCode_234.回文链表
题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
图解
代码实现
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null){
return true; //只有一个结点或者没有结点时默认为回文链表
}
ListNode middle=findMiddle(head); //找出中间结点
middle.next=reverseList(middle.next); //对中间结点以后的元素进行反转
ListNode h=head; //指针h从第一个结点开始
ListNode p=middle.next; //指针p从中间结点下一个位置开始
while(p!=null&&h.val==p.val){ //p!=null要放在h.val==p.val的左边否则会发生逻辑错误
p=p.next;
h=h.next;
}
return p==null; //图解注释
}
private ListNode findMiddle(ListNode head){ //实现寻找中间结点
if(head==null||head.next==null){
return null;
}
ListNode fast=head.next;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow; //当fast为空,此时slow所指的位置就是中间结点
}
private ListNode reverseList(ListNode head){ //实现链表反转
if(head==null||head.next==null){
return head;
}
ListNode h=reverseList(head.next);
head.next.next=head;
head.next=null;
return h;
}
}