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


    题目描述

    输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
    代码
    思路
    链表的特点,如果两个链表有一个公共点,则后面的都会重叠。如果两个链表长度不一,先让长的先走几步,两个链表再一起走
    编程注意点
    while pHead1 != pHead2 and pHead1 and pHead2:
    把此条语句写成了如下,一直调试不通,错误使用了not
    while pHead1 != pHead2 and not pHead1 and not pHead2:
     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         if not pHead1 or not pHead2:
    10             return None
    11         # 分别计算两个链表的长度
    12         n1 = 0
    13         n2 = 0
    14         p1 = pHead1
    15         p2 = pHead2
    16         while p1:
    17             n1 += 1
    18             p1 = p1.next
    19         while p2:
    20             n2 += 1
    21             p2 = p2.next
    22         #p1 = pHead1
    23         #p2 = pHead2
    24         if n1>n2: #第一个链表长,让第一个链表先走n步
    25             n = n1 -n2
    26             while n!= 0:
    27                     n = n-1
    28                     pHead1 = pHead1.next
    29         else:
    30             n = n2 -n1
    31             while n!= 0:
    32                     n = n-1
    33                     pHead2 = pHead2.next
    34         while pHead1 != pHead2 and pHead1 and pHead2:
    35                 pHead1 = pHead1.next
    36                 pHead2 = pHead2.next
    37         if pHead1 == pHead2:
    38             return pHead1
    39         else:
    40             return None
    41     
  • 相关阅读:
    不使用BeanUtils,利用Java反射机制:表单数据自动封装到JavaBean
    VS2010水晶报表的添加与使用
    使用SelectClipRgn注意事项
    使用SelectClipRgn注意事项
    使用事件CreateEvent注意事项
    【转】Delphi内嵌ASM简易教程
    栈顶和栈底示意图
    【转】对ARM堆栈的理解
    UISegmentedControl的基本使用
    C语言小知识总结
  • 原文地址:https://www.cnblogs.com/shuangcao/p/12780626.html
Copyright © 2020-2023  润新知