给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
class Solution {
public boolean isPalindrome(ListNode head) {//此函数判断是否为回文链表
if(head==null&&head.next==null)//零元素,一个元素,返回true
return true;
ListNode slow=head;
ListNode fast=head;//定义快慢指针,快指针走过的路径刚好是慢指针的两倍
while(fast.next!=null&&fast.next.next!=null)//快指针能走慢指针才能走
{
slow=slow.next;
fast=fast.next.next;
}//前方的路径是奇数fast会停在倒数第二位元素,前方的路径是偶数fast会停留在最后一个元素
//可以根据fast和slow走过的路径关系找到slow位置
slow=reverse(slow.next);
//如链表:1—>2->3->4->5->null会变成如图下所示
// 1-> 2 -> 3-> 4 <-5 (4->null)
//head(指向1) slow(指向-5)
while(slow!=null)
{
if(slow.val !=head.val)//判断
return false;
slow=slow.next;
head=head.next;
}
return true;
}
public ListNode reverse(ListNode head)//定义反转函数将链表反转
{//迭代
ListNode pre=null;
ListNode next=null;
while(head!=null)
{
next=head.next;//next指向第二个元素
head.next=pre;//head对应的元素与前一个元素链接,同时与后一个元素断开链接(第一次while循环指向空)
pre=head;//pre指向head所在元素
head=next;//head遍历到第二个元素
//整个过程就是断开链接,改变链接方向并且从新接上链接
//如链表在运行过程中的变化:3—>4->null => null<-3 4->null => null<-3<-4
}
return pre;//pre指向新链表的首元素
}
}
//链表类
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}