其他分享
首页 > 其他分享> > 关于链表的中点

关于链表的中点

作者:互联网

单链表的中点

我们这就可以直接取前重点来比较嘛。
代码的话,要想验证回文,直接找到前中点的结点,然后反转后面的链表,再l1从开始比,l2从以反转的地方开始,直到比完l2就行了。
简单的一道题。
不过有些边界条件需要主要一下,以免出现空指针异常。

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    public boolean isPail (ListNode head) {
        ListNode preHead=new ListNode(-1);
        preHead.next=head;
        ListNode mid=findMid(head);
        ListNode tmp=mid.next;
        mid.next=null;
        ListNode l2 = reverse(tmp);
        ListNode l1 = head;
        while(l2!=null){
            if(l1.val!=l2.val) return false;
            l1=l1.next;
            l2=l2.next;
        }
        
        return true;
    }
    //找 前 中点嘛
    public ListNode findMid(ListNode head){
        ListNode preHead=new ListNode(-1);
        preHead.next=head;
        ListNode slow=head;
        ListNode fast=head.next;
        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow;   
    }
    public ListNode reverse(ListNode head){
        ListNode cur=head;
        ListNode pre=null;
        while(cur!=null){
            ListNode tmp=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tmp;
        }
        return pre;
    }
}

标签:head,ListNode,cur,next,链表,l2,关于,null,中点
来源: https://www.cnblogs.com/ArtiaDeng-blog/p/16146986.html