给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
法一:转换成数组然后双指针比较,直到left不满足小于right.
public boolean isPalindrome(ListNode head) {
List<Integer> vals=new ArrayList<>();
ListNode current=head;
while (current!=null){
vals.add(current.val);
current=current.next;
}
int left=0,right=vals.size()-1;
while (left<right){
if(vals.get(left)!=vals.get(right)){
return false;
}
left++;
right--;
}
return true;
}
法二:快慢指针锁定前半串的末尾,然后将末尾的next(后半串的开头)进行链表反转,然后用指针逐一比较,直至一方为null
public boolean isPalindrome(ListNode head) {
if(head==null){
return true;
}
ListNode firstHalfEnd=endOfFirstHalf(head);
ListNode secondHalfStart=reverseList(firstHalfEnd.next);
ListNode p1=head;
ListNode p2=secondHalfStart;
while (p1!=null&&p2!=null){
if(p1.val!=p2.val){
return false;
}
p1=p1.next;
p2=p2.next;
}
return true;
}
private ListNode endOfFirstHalf(ListNode head){
ListNode fast=head;
ListNode slow=head;
while (fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
private ListNode reverseList(ListNode head){
ListNode pre=null;
ListNode cur=head;
while (cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}