代码随想录 day4

160. 相交链表

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int sizeA=0,sizeB=0;
        ListNode tA=headA,tB=headB;
        while(tA!=null){
            tA=tA.next;
            sizeA++;
        }
        while(tB!=null){
            tB=tB.next;
            sizeB++;
        }
        tA=headA;tB=headB;
        if(sizeA>=sizeB){//移位
            for(int i=sizeA-sizeB;i>0;i--){
                tA=tA.next;
            }
        }else{
            for(int i=sizeB-sizeA;i>0;i--){
                tB=tB.next;
            }
        }
        while(tA!=tB){
            if(tA==null)return null;
            tA=tA.next;tB=tB.next;
        }
        return tA;

    }

19. 删除链表的倒数第 N 个结点

public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head.next==null)return null;
        int size=0;
        ListNode t=head;
        while(t!=null){t=t.next;size++;}
        if(n==size){
            return head.next;
        }
        t=head;
        for(int i=size-n;i>1;i--){
            t=t.next;
        }
        t.next=t.next.next;
        return head;
    }

142. 环形链表 II

快慢指针
判断一定要写全

public ListNode detectCycle(ListNode head) {
        ListNode step1=head,step2=head;
        while(step1!=null&&step2!=null){
            step1=step1.next;
            if(step2.next!=null)step2=step2.next.next;
            else return null;
            if(step1==step2){
                step2=head;
                while(step2!=step1){
                    step1=step1.next;
                    step2=step2.next;
                }return step2;
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值