(链表练习)相交链表---数据结构

89 篇文章 0 订阅
38 篇文章 1 订阅

要求:
找到两个单链表相交的起始节点。
在这里插入图片描述
注意:
这里相交结点的值为8,为什么不是1呢?因为所谓结点相交,需要满足结点相等(指向同一对象),而不只是结点值相等。
思路:
以相交后的长度相等为基准,做比较。
实现:

public class getIntersectionNode {
    public static void main(String[] args) {
        ListNode head1=new ListNode(4);
        ListNode n2=new ListNode(1);
        ListNode n3=new ListNode(8);
        ListNode n4=new ListNode(4);
        ListNode n5=new ListNode(5);
        ListNode head2=new ListNode(5);
        ListNode l2=new ListNode(0);
        ListNode l3=new ListNode(1);
        head1.next=n2;
        n2.next=n3;
        n3.next=n4;
        n4.next=n5;
        n5.next=null;
        head2.next=l2;
        l2.next=l3;
        l3.next=n3;
        n3.next=n4;
        n4.next=n5;
        n5.next=null;//以上 按示例1构造两个链表
        System.out.println("链表1为:");
        print(head1);
        System.out.println("链表2为:");
        print(head2);
        System.out.println("两个链表相交的起始结点为:");
        ListNode startNode = get(head1, head2);
        System.out.println(startNode);
    }

    public static ListNode get(ListNode head1,ListNode head2){
        int count1=getCount(head1);//计算链表1长度
        int count2=getCount(head2);//计算链表2长度

        ListNode cur1=head1;
        ListNode cur2=head2;

        //以比较相同长度为基准
        if (count1>count2){
            for (int i=0;i<count1-count2;i++){
                cur1=cur1.next;
            }
        }
        else if (count2>count1){
            for (int i=0;i<count2-count1;i++){
                cur2=cur2.next;
            }
        }
        while (cur1!=cur2){
            cur1=cur1.next;
            cur2=cur2.next;
        }
        return cur2;
    }

    private static int getCount(ListNode head) {//计算长度
        ListNode cur=head;
        int count=1;
        while (cur.next!=null){
            cur=cur.next;
            count++;
        }
        return count;
    }
    public static void print(ListNode head) {//打印
        ListNode cur = head;
        while (cur != null) {
            System.out.println(cur.toString());
            cur = cur.next;
        }
    }
}

执行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值