一、题目
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
二、链表反转模板
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null) {
ListNode nextN=cur.next;
cur.next=pre;
pre=cur;
cur=nextN;
}
return pre;
}
三、快慢指针模板
public ListNode endOfFirstHalf(ListNode head) {
ListNode low=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null) {
low=low.next;
fast=fast.next.next;
}
return low;
}
四、解题思路
使用快慢指针,找到后半链表,将其反转,判断是否为回文链表。最后记得将后半链表恢复,通常题目并不想让你破坏原来的链表哦!
五、代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null) {
return true;
}
ListNode p1=head;//第一个链表,p1指向前一半链表
ListNode endofFirstNode=endOfFirstHalf(head);//endofFirstNode指向前一半链表的尾节点
ListNode p2=reverseList(endofFirstNode.next);//将后半链表进行反转
boolean flag=true;
while(flag&&p2!=null) {
if(p1.val!=p2.val) {
flag=false;
}
p1=p1.next;
p2=p2.next;
}
endofFirstNode.next=reverseList(p2);//将后半链表恢复
return flag;
}
//链表反转模板
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null) {
ListNode nextN=cur.next;
cur.next=pre;
pre=cur;
cur=nextN;
}
return pre;
}
//快慢指针模板
public ListNode endOfFirstHalf(ListNode head) {
ListNode low=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null) {
low=low.next;
fast=fast.next.next;
}
return low;
}
}