zoukankan      html  css  js  c++  java
  • 26.leetcode160_intersection_of_two_linked_lists

    1.题目描述

    Write a program to find the node at which the intersection of two singly linked lists begins.

    For example, the following two linked lists:

    A:          a1 → a2
                       ↘
                         c1 → c2 → c3
                       ↗            
    B:     b1 → b2 → b3
    

    begin to intersect at node c1.

    Notes:

      • If the two linked lists have no intersection at all, return null.
      • The linked lists must retain their original structure after the function returns.
      • You may assume there are no cycles anywhere in the entire linked structure.
      • Your code should preferably run in O(n) time and use only O(1) memory.

    找出双链表交叉处的指针,没有的话返回None。

    2.题目分析

    题目给的限制条件比较多,比较令人难受的是不能改变链表结构(不能做标记)。所以采用与142题类似的解法,双指针同时前进一个节点找到相同节点,避免n^2的重复比较。

    3.解题思路

    ①从后向前取相同长度(因为相同的是后半截)

    ②从等长度处开始同时遍历等长度

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def getIntersectionNode(self, headA, headB):
     9         """
    10         :type head1, head1: ListNode
    11         :rtype: ListNode
    12         """
    13         l1=0
    14         l2=0
    15         p1=headA
    16         p2=headB
    17         while p1!=None:
    18             l1+=1
    19             p1=p1.next
    20         while p2!=None:
    21             l2+=1
    22             p2=p2.next
    23         p1=headA
    24         p2=headB
    25         n=l1-l2
    26         if n>0:
    27             for i in range(0,n):
    28                 p1=p1.next
    29         if n<0:
    30             for i in range(0,-n):
    31                 p2=p2.next
    32         while p1!=None:
    33             if p1==p2:
    34                 return p1
    35             else:
    36                 p1=p1.next
    37                 p2=p2.next
    38         return None
    39                 
  • 相关阅读:
    C#高级编程第11版
    C#特性
    设计模式 单一职责原则
    设计模式 依赖倒置原则
    C# 预处理指令
    毕业设计 python opencv实现车牌识别 矩形矫正
    毕业设计 python opencv实现车牌识别 颜色判断
    毕业设计 python opencv实现车牌识别 界面
    南昌大学航天杯第二届程序设计竞赛校赛网络同步赛 I
    南昌大学航天杯第二届程序设计竞赛校赛网络同步赛 G
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8445604.html
Copyright © 2011-2022 走看看