请判断一个链表是否为回文链表。
示例 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 slow=head;
ListNode fast=head;
//找中点位置
while(fast.next!=null &&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//逆置链表
ListNode reverseNode=reverseList(slow);
//进行比较
while(head!=null && reverseNode!=null){
if(head.val!=reverseNode.val){
return false;
}
head=head.next;
reverseNode=reverseNode.next;
}
return true;
}
//将链表进行逆置
public ListNode reverseList(ListNode head){
if(head==null){
return head;
}
ListNode pre=head;
ListNode cur=head.next;
ListNode temp;
while(cur!=null){
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
head.next=null;
return pre;
}
}
判断链表是否为回文
本文介绍了一种判断链表是否为回文的方法,通过找到链表的中点,然后逆置后半部分的链表,最后比较两部分是否完全相同。此方法适用于所有类型的链表。
4010

被折叠的 条评论
为什么被折叠?



