在无环单链表中找公共部分

目录

题目描述:

解法1.

解法2.


题目描述:

给你两个单链表的头节点 head1 和 head2,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null。

解法1.


class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; this.next = null; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        if(headA==null || headB==null){
            return null;
        }

        ListNode nestA = headA;
        ListNode nestB = headB;
        while(nestA != nestB){
            nestA = nestA==null ? headA : nestA.next;
            nestB = nestB==null ? headB : nestB.next;
        }

        return nestA;
    }

解法2.

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

 public static Node getIntersectionNode(Node head1,Node head2){
        if(head1==null || head2==null){
            return null;
        }
        Node cur1 = head1;
        Node cur2 = head2;
        int n = 0;
        while(cur1!=null){
            n++;
            cur1 = cur1.next;
        }
        while(cur2!=null){
            n--;
            cur2 = cur2.next;
        }
        if(cur1!=cur2){
            return null;
        }
        cur1 = n > 0 ? head1 : head2;
        cur2 = cur1 == head1 ? head2 : head1;
        n = Math.abs(n);
        while(n!=0){
            n--;
            cur1 = cur1.next;
        }
        while(cur1!=cur2){
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return cur1;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值