码迷,mamicode.com
首页 > 其他好文 > 详细

26.leetcode160_intersection_of_two_linked_lists

时间:2018-02-12 22:23:05      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:解法   type   没有   range   amp   +=   tno   ram   tin   

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                 

 

26.leetcode160_intersection_of_two_linked_lists

标签:解法   type   没有   range   amp   +=   tno   ram   tin   

原文地址:https://www.cnblogs.com/19991201xiao/p/8445604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!