链表之第一个公共子节点

算法通关村第一关 —— 链表白银挑战笔记

结合上篇中叙述的数据结构之链表 ,解决下题

使用四种方法,Hash、栈、链表拼接、差和四种方法解决寻找两链表第一个公共子节点问题

情景设定

        输入两个链表,已知两个链表在相交处会形成单链表,求相交点的值;

        

        

零、测试代码

public static void main(String[] args) throws Exception {
        Node<Integer> one = new Node<>(1);
        Node<Integer> two = new Node<>(2);
        Node<Integer> three = new Node<>(3);
        Node<Integer> four = new Node<>(4);
        Node<Integer> five = new Node<>(5);
        Node<Integer> six = new Node<>(6);
        Node<Integer> seven = new Node<>(7);
        Node<Integer> eight = new Node<>(8);

        Link<Integer> link1 = Struct.getLink(new Node[]{one, two, three, five, six, seven, eight});
        Link<Integer> link2 = Struct.getLink(new Node[]{four, five, six, seven, eight});
        System.out.println(hash(link1, link2).getVal());
        System.out.println(stack(link1, link2).getVal());
        System.out.println(append(link1, link2).getVal());
        System.out.println(abs(link1, link2).getVal());

}
public class Struct {

    public static Link<Integer> getLink(Node<Integer>[] nodes) {
        Link<Integer> link = new Link<>();
        Arrays.asList(nodes).forEach(link::append);
        return link;
    }

    public static boolean isLinkBlank(Link<Integer> link){
        return link == null || link.getLength() <= 0;
    }
}

一、Hash

        使用hash结构,如java中的HashSet,先将第一个链表的节点放到hash中,然后遍历第二个链表,判断hash中是否有相同的节点

        使用集合List也是类似的方式

public static Node<Integer> hash(Link<Integer> link1, Link<Integer> link2) throws Exception {
        Set<Node<Integer>> sets = new HashSet<>();
        if (Struct.isLinkBlank(link1) || Struct.isLinkBlank(link2)) {
            throw new LinkException("链表为空");
        }
        Node<Integer> node = link1.getHead();
        sets.add(node);
        //放入set中
        while (node.getNext() != null) {
            sets.add(node.getNext());
            node = node.getNext();
        }
        Node<Integer> node2 = link2.getHead();
        //遍历第二个链表
        while (node2.getNext() != null) {
            if (sets.contains(node2)) {
                return node2;
            }
            node2 = node2.getNext();
        }
        return null;
}

二、栈

        使用栈来找出公共子节点,首先得先创建两个栈,把两链表中的数据依次分别压到栈中,由于栈的结构为后进先出,所以会从最后一个节点开始比较,此时,两个栈依次分别弹栈,弹出的数据作比较,若相等则用临时变量保存,然后继续弹栈,直到有一组不相等的样品为止,返回上一个相等的节点

public static Node<Integer> stack(Link<Integer> link1, Link<Integer> link2) {
        if (Struct.isLinkBlank(link1) || Struct.isLinkBlank(link2)) {
            throw new LinkException("链表为空");
        }
        Stack<Node<Integer>> stack1 = new Stack<>();
        Stack<Node<Integer>> stack2 = new Stack<>();

        Node<Integer> head1 = link1.getHead();
        Node<Integer> head2 = link2.getHead();
        //压栈
        while (head1 != null) {
            stack1.push(head1);
            head1 = head1.getNext();
        }
        while (head2 != null) {
            stack2.push(head2);
            head2 = head2.getNext();
        }

        Node<Integer> preNode = null;
        //弹栈
        while (stack1.size() > 0 && stack2.size() > 0) {
            Node<Integer> pop1 = stack1.pop();
            Node<Integer> pop2 = stack2.pop();
            if (pop1 != pop2) {
                return preNode;
            }
            preNode = pop1;
        }

        return null;

}

三、拼接两个字符串

        意思就是把两个链表拼接起来,如

        A:0 - 1 - 2 - 3 - 6 - 7

        B:4 - 5 - 6 - 7

        分别拼成AB、BA

        AB:0 - 1 - 2 - 3 - 4 - 5 - 4 - 5 - 6 - 7

        BA:4 - 5 - 6 - 7 - 0 - 1 - 2 - 3 - 4 - 5

        此时从头开始遍历,会发现第一次相遇的地方“4”即为第一个公共子节点

        so为什么呢?我们从数学的角度出发分析一下,设

        a = 0 - 1 - 2 - 3; b = 6 - 7; c = 4 - 5

        有:A = a + b;

               B = c + b;

               AB = a + b + c + b;

               BA = c + b + a + b;

               ∵  a != c 且a、b、c中元素各不相同(有相同的就变成环啦)

               ∴ length(a + b + c) =  length(c + b + a) 且 无a、b、c无交集

               ∴ b处为第一个公共子节点

        

        代码中可以在当node1 = null时,把node1指向node2.head,节约空间,但要注意的是,需要在while中再判断node1 != node2,防止陷入死循环

public static Node<Integer> append(Link<Integer> link1, Link<Integer> link2) {
        if (Struct.isLinkBlank(link1) || Struct.isLinkBlank(link2)) {
            throw new LinkException("链表为空");
        }

        Node<Integer> head1 = link1.getHead();
        Node<Integer> head2 = link2.getHead();
        Node<Integer> node1 = head1;
        Node<Integer> node2 = head2;
        while (node1 != node2) {
            node1 = node1.getNext();
            node2 = node2.getNext();
            //防止两链表无公共子节点时陷入死循环
            if (node1 != node2) {
                if (node1 == null) {
                    node1 = head2;
                }
                if (node2 == null) {
                    node2 = head1;
                }
            }
        }
        return node1;
}

        

四、差和双指针

        意思很简单,如果俩链表等长,直接逐个遍历直到相同节点即可,若两链表不等长,就先算出他们的差值,先让长的链表先走相差的步数,然后再逐个遍历直到相同节点;

        

public static Node<Integer> abs(Link<Integer> link1, Link<Integer> link2) {
        if (Struct.isLinkBlank(link1) || Struct.isLinkBlank(link2)) {
            throw new LinkException("链表为空");
        }
        int length1 = link1.getLength();
        int length2 = link2.getLength();
        int count = 0;

        Node<Integer> node1 = link1.getHead();
        Node<Integer> node2 = link2.getHead();
        if (length1 >= length2) {
            int abs = length1 - length2;
            while (count < abs) {
                count++;
                node1 = node1.getNext();
            }
        } else {
            int abs = length2 - length1;
            while (count < abs) {
                count++;
                node2 = node2.getNext();
            }
        }
        while (node1 != node2){
            node1 = node1.getNext();
            node2 = node2.getNext();
        }

        return node1;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值