关闭

(LeetCode)Intersection of Two Linked Lists --- 两个链表的交集

589人阅读 评论(0) 收藏 举报
分类:

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.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


解题分析:

对于这个题目来说,我的做法就是先判断出哪个LinkedList 比较小。

然后可循环比较最小的次数,来达到最高的效率,没有环,更好判断一些。

加上条件判断,就可以判断出来是否末尾的串有交集。

# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        listA= []
        listB= []
        if headA == None or headB == None:
            return None
        while 1:
            if headA == None:
                break
            listA.append(headA.val)
            headA = headA.next

        while 1:
            if headB == None:
                break
            listB.append(headB.val)
            headB = headB.next

        if listA[-1] != listB[-1]:
            return None
        if len(listA) < len(listB):
            minLen = len(listA)
        else:
            minLen = len(listB)
        for i in range(1, minLen + 1):
            if listA[-i] != listB[-i]:
                return ListNode(listA[-i + 1])
            if i == minLen:
                return ListNode(listA[-i])






0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1396559次
    • 积分:26971
    • 等级:
    • 排名:第231名
    • 原创:1362篇
    • 转载:21篇
    • 译文:7篇
    • 评论:202条
    Social NetWork
    博客专栏
    最新评论