0
点赞
收藏
分享

微信扫一扫

算法---相交链表(Java)

岛上码农 2022-04-13 阅读 68
算法

题目:

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

图示两个链表在节点 c1 开始相交:
在这里插入图片描述

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构 。

解决思路:

在这里插入图片描述
在这里插入图片描述

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode-solutio-a8jn/

解决方法:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}

我的解决方法:

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode head1 = headA;
        ListNode head2 = headB;

        boolean first = false;
        boolean second = false;

        while (head1 != null && head2 != null) {
            if (head1 == head2){
                return head1;
            }
            if (head1.next != null) {
                head1 = head1.next;
            }else {
                if (!first) {
                    head1 = headB;
                    first = true;
                }else {
                    head1 = null;
                }
            }

            if (head2.next != null) {
                head2 = head2.next;
            }else {
                if (!second){
                    head2 = headA;
                    second = true;
                }else {
                    head2 = null;
                }
            }
        }
        return null;
    }

写了一坨。。

思考:

利用a + c + b = b + c + a

在这里插入图片描述

举报

相关推荐

0 条评论