腾讯精选50题(5)--160.相交链表

在这里插入图片描述在这里插入图片描述在这里插入图片描述
解法一:双指针,循环遍历(这个牛批)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null) return null;
        ListNode cura = headA;
        ListNode curb = headB;
        //定义两个指针,首先分别指向两个链表头,然后遍历,当其中一条指向null(就是到尾节点),就指向另一个链表的头,
        //然后再重复一次遍历,这样的话,既是两条链表都遍历了相同的长度,链表A+链表B(链表B+链表A),如果有相同的节点的话,最后A+B的节点时会相交,否则即是NULL,也是相同节点,这时候就退出循环,所以while(cura!=curb)
        while(cura!=curb){
            cura = cura==null? headB:cura.next;
            curb = curb==null? headA:curb.next;
        }
        return cura;
    }
}

在这里插入图片描述 解法二:对齐链表,然后遍历

/**
     *  计算出headA和headB中那个链表最长,计算出长度
     *  把长度较长的链表偏移,使两个链表对齐。
     *  最后同同时遍历两个链表,如果相等 说明它们相交了
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        int a=getLength(headA);
        int b=getLength(headB);

//       把长度较长的链表偏移,使两个链表对齐。
        if(a>b){
            for (int i = 0; i <a-b ; i++) {
                headA=headA.next;
            }
        }else{
            for (int i = 0; i <b-a ; i++) {
                headB=headB.next;
            }
        }
        //最后同同时遍历两个链表,如果相等 说明它们相交了
            while (headA!=null && headB!=null && headA!=headB){
                headA=headA.next;
                headB=headB.next;
            }

           return  headA;
    }

    public  int getLength(ListNode head){
        int count=0;
        while (head!=null){
            ++count;
            head=head.next;
        }
        return  count;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值