python求解LeetCode习题Intersection of Two Linked Lists

题目

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.


翻译:

给定两个链表,输出交点

思路:

将链表划分为列表形式,求交集,返回交集中索引最小值处元素即可


具体实现如下:

#!usr/bin/env python
#encoding:utf-8


'''
__Author__:沂水寒城
功能:Find Intersection of Two Linked Lists
'''

def find_intersect_node(link1, link2):
    '''
    寻找给定的两个链表的交点
    '''
    link_list1=link1.split('->')
    link_list2=link2.split('->')
    intersect_list=list(set(link_list1)&set(link_list2))
    index_list=[link_list1.index(one) for one in intersect_list]
    #print index_list
    print '链表交点为:', link_list1[min(index_list)]


if __name__ == '__main__':
    str1='a->b->c->d->e->f'
    str2='o->p->q->r->s->->d->e->f->m->n'
    find_intersect_node(str1, str2)


结果如下:


链表交点为: d
[Finished in 0.3s]



你可能感兴趣的:(面试工作,编程技术,python实践)