问题:输入两个链表,找出他们的第一个公共结点

思考:链表的公共结点意味着该结点的value值以及next相同,则两个链表有相同的后缀。

   两种方式:1.分别遍历两个链表,计算长度,计算链表差值,长链表先走差值个,短链表开始走,比较两个链表的后缀。2.不计算长度,同时遍历两个链表,当链表中的结点为空时交换链表头指针,追赶,当有公共结点时跳出循环。

这里给出方法2代码:

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 class Solution:
 7     def FindFirstCommonNode(self, pHead1, pHead2):
 8         # write code here
 9         p1 = pHead1
10         p2 = pHead2
11         while p1 != p2:
12             if p1 == None :
13                 p1 = pHead2 
14             else:
15                 p1 = p1.next
16             if p2 == None :
17                 p2 = pHead1 
18             else:
19                 p2 = p2.next
20         return p1

 

posted on 2017-08-07 10:21  刀刀121  阅读(123)  评论(0编辑  收藏  举报