程序员面试金典2.6-2.8

2.6回文链表

在这里插入图片描述
思路很简单,就是后半段翻转链表进行比较
然后开局我想用for去先求一遍len,后来发现可以用快慢指针直接找到中点
然后翻转链表的flip也不会写了。最后再轻松的比较一下是否相同就可以啦。核心是翻转链表flip

class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        ListNode new_head=flip(slow);
        while(new_head!=null){
            if(new_head.val != head.val) return false;
            new_head=new_head.next;
            head=head.next;
        }
        return true;
    }
    
    ListNode flip(ListNode head){
        ListNode cur=head;
        ListNode pre=null;
        while(cur!=null){
            ListNode post=cur.next;
            cur.next=pre;
            pre=cur;
            cur=post;
        }
        return pre;
    }
}

2.7链表相交

在这里插入图片描述
数学思路烂熟于心,写代码写了半天写不出来。。。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        ListNode h1 = headA, h2 = headB;

        while (h1 != h2) {

            h1 = h1 == null ? headB : h1.next;
            h2 = h2 == null ? headA : h2.next;
        }

        return h1;  
        
    }
}

他这里是可以让H1d等于一次空
如果是相交,那肯定能出来
如果不相交,h1最后是headB的末尾的null;h2最后是headA末尾的null,这样返回的也是null

2.8环路检测(*)

在这里插入图片描述

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=null && fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow) break;
        }
        if(fast==null || fast.next==null) return null; //可能是while条件不满足,则是无环
        slow=head;
        while(slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return slow;
       
        
    }
}

数学推导烂熟了,主要是注意一下无环条件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值