24、链表-回文链表

思路:

回文链表就是两个指针各从首 尾 开始遍历,实时相等,那么就是回文链表,或者关于中线对称。

第一种方式

集合方式实现很简单不再赘述,代码如下

 //直接使用一个栈来校验,回文正过来 逆过来 都一样,正好利用栈的先进后出逆序这个链表,在进行比对
    public boolean isPalindrome(ListNode head) {
        if (head==null){
            return false;
        }
        //定义一个栈
        ListNode cur=head;
        Stack<ListNode> stack = new Stack<>();
        while (cur!=null){
            stack.push(cur);
            cur=cur.next;
        }
        while (head!=null){
            //比较节点的值,而不是节点本身
            if (head.val!=stack.pop().val){
                return false;
            }
            head=head.next;
        }
        return true;
    }

第二种方式:

如果将原链表反转 然后在与原链表相比 是否相等,如果相等那么他就是回文链表。

代码如下:

    public static boolean isPalindrome02(ListNode head) {
        if (head==null){
            return false;
        }
        ListNode node = copy(head);
        //反转这个复制的链表
        ListNode pre=null;
        ListNode next;
        while (node!=null){
            next=node.next;
            node.next=pre;
            pre=node;
            node=next;
        }
        while (head!=null){
            if (head.val!=pre.val){
                return false;
            }
            head=head.next;
            pre=pre.next;
        }
        return true;
    }

第三种方式:

可以在中位节点到尾节点部分进行反转,然后利用头尾指针相向遍历。然后再将反转的部分恢复,代码如下:

class Solution {
    public static boolean isPalindrome(ListNode head) {
        if (head==null){
            return false;
        }

        //获取上中位数节点
        ListNode midOrUpMid = getMidOrUpMid(head);
        //反转当前节点
        ListNode pre = reverse(midOrUpMid);
        ListNode L=head;
        ListNode R=pre;
        //回文链表就是验证  对于i关于中位数对称=>  node(i)=node(N-1-i)===>L==R  L++ R--
        while (L!=null&&R!=null){
            if (L.val!=R.val){
                return false;
            }
            L=L.next;
            R=R.next;
        }

        //修正head
        ListNode reverse = reverse(pre);
        midOrUpMid.next=reverse.next;
        return true;
    }

    private static ListNode reverse(ListNode midOrUpMid) {
        ListNode pre=null;
        ListNode next;
        while (midOrUpMid !=null){
            next= midOrUpMid.next;
            midOrUpMid.next=pre;
            pre= midOrUpMid;
            midOrUpMid =next;
        }
        return pre;
    }
     public static ListNode getMidOrUpMid(ListNode head){
      if (head==null||head.next==null||head.next.next==null){
          return head;
      }
      ListNode slow=head.next;
      ListNode fast=head.next.next;

      while (fast.next!=null&&fast.next.next!=null){
          slow=slow.next;
          fast=fast.next.next;
      }
      return slow;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值