Python两个链表的第一个公共结点

本文阅读 1 分钟
首页 Python笔记 正文

首先依次遍历两个链表,记录两个链表的长度m和n,如果 m > n,那么我们就先让长度为m的链表走m-n个结点,然后两个链表同时遍历,当遍历到相同的结点的时候停止即可。对于 m < n,同理。

  1. '''
  2. 输入两个链表,找出它们的第一个公共结点。
  3. '''
  4. # -*- coding:utf-8 -*-
  5. class ListNode:
  6. def __init__(self, x):
  7. self.val = x
  8. self.next = None
  9. class Solution:
  10. def FindFirstCommonNode(self, pHead1, pHead2):
  11. nLength1 = self.GetListLength(pHead1)
  12. nLength2 = self.GetListLength(pHead2)
  13. nLengthDiff = abs(nLength1 - nLength2)
  14. if nLength1 > nLength2:
  15. pListHeadLong = pHead1
  16. pListHeadShort = pHead2
  17. else:
  18. pListHeadLong = pHead2
  19. pListHeadShort = pHead1
  20. for i in range(nLengthDiff):
  21. pListHeadLong = pListHeadLong.next
  22. while pListHeadLong != None and pListHeadShort != None and pListHeadLong != pListHeadShort:
  23. pListHeadLong = pListHeadLong.next
  24. pListHeadShort = pListHeadShort.next
  25. pFirstCommonNode = pListHeadLong
  26. return pFirstCommonNode
  27. def GetListLength(self, pHead):
  28. nLength = 0
  29. while pHead != None:
  30. pHead = pHead.next
  31. nLength += 1
  32. return nLength
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python数组中的逆序对
« 上一篇 01-21
Python数字在排序数组中出现的次数
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18497 篇
  • 评论总数:
    53345 条
  • 标签总数:
    8873 个
  • 总浏览量:
    23080839 次
  • 最后更新:
    3月27日

最多点赞

随便看看

标签TAG