zoukankan      html  css  js  c++  java
  • 160. 相交链表

    题目:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

    自己的方法:暴力方法:

    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode tempb=new ListNode(-999);
            while( headA!=null)
            {
                ListNode tempa=headA;
                for(tempb=headB;tempb!=null;tempb=tempb.next)
                {
                    if(tempb==tempa)
                    {
                        return tempb;
                    }
                }
    
                headA=headA.next;
            }
            return null;
        }
    }

    其它方法:

    解一:

    计算两个链表各自长度,长度之差为 diff
    让较长链表先走 diff 步
    长短链表再同步往前走,在第一个相同节点停下
    如果走完了链表没有相遇,说明两个链表不相交

    class Solution:
        def getIntersectionNode(self, L1: ListNode, L2: ListNode) -> ListNode:
    
            def length(L):
                n = 0
                while L:
                    n += 1; L = L.next
                return n 
            
            len1, len2 = length(L1), length(L2)
            if len1 > len2:
                L1, L2 = L2, L1
            for _ in range(abs(len1 - len2)):
                L2 = L2.next
            while L1 and L2 and L1 is not L2:
                L1, L2 = L1.next, L2.next
            return L1

    解二:

    • 长短链表相互拼接,遇到相同节点跳出循环,该节点即为相交节点
    class Solution:
        def getIntersectionNode(self, L1: ListNode, L2: ListNode) -> ListNode:
            h1, h2 = L1, L2
            while h1 is not h2:
                h1 = h1.next if h1 else L2
                h2 = h2.next if h2 else L1
            return h1
  • 相关阅读:
    2. 环形路加油
    1. 元素累加
    开始在线练习50题。
    C# 搜索关键词
    Python调用OpenCV几何变换
    Tensorflow加载多幅图像进一个tensor
    Cmake构建OpenCV测试例子
    Linux利用本地http下载解决一些需要联网下载的问题
    Python调用OpenCV算术操作
    Python调用OpenCV阈值化
  • 原文地址:https://www.cnblogs.com/William-xh/p/13637215.html
Copyright © 2011-2022 走看看