zoukankan      html  css  js  c++  java
  • 【链表】两个链表的第一个公共结点

    输入两个链表,找出它们的第一个公共结点。

     1 public class Solution {
     2     
     3     /**
     4      * 思路:两个链表相交,存在公共的链表尾,根据链表长度的差值,移动指针,找到第一个相同的节点,即为第一个公共节点
     5      * @param pHead1
     6      * @param pHead2
     7      * @return
     8      */
     9     public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
    10 
    11         if (pHead1 == null || pHead2 == null) {
    12             return null;
    13         }
    14 
    15         int d = 0;
    16 
    17         ListNode p1 = pHead1;
    18         ListNode p2 = pHead2;
    19 
    20         int length1 = 0;
    21         while (pHead1 != null) {
    22             length1++;
    23             pHead1 = pHead1.next;
    24         }
    25 
    26         int length2 = 0;
    27         while (pHead2 != null) {
    28             length2++;
    29             pHead2 = pHead2.next;
    30         }
    31 
    32         if (length1 > length2) {
    33             d = length1 - length2;
    34 
    35             while (d > 0) {
    36                 p1 = p1.next;
    37                 d--;
    38             }
    39         } else if (length1 < length2) {
    40             d = length2 - length1;
    41 
    42             while (d > 0) {
    43                 p2 = p2.next;
    44                 d--;
    45             }
    46         } else {
    47             return p1;
    48         }
    49 
    50         while (p1 != null) {
    51             if (p1 == p2) {
    52                 break;
    53             }
    54             p1 = p1.next;
    55             p2 = p2.next;
    56         }
    57         return p1;
    58     }
    59 }
    60 
    61 class ListNode {
    62     int val;
    63     ListNode next = null;
    64 
    65     ListNode(int val) {
    66         this.val = val;
    67     }
    68 }
  • 相关阅读:
    参数默认值
    调用外部 DLL 中的函数(1. 早绑定)
    Delphi 运行时错误信息表
    分享:PyPyODBC 0.9.2发布 纯Python实现的pyodbc替代库
    我的书单
    我的书单
    Philip Guo googler
    我的书单
    isbn2title
    我的书单
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/5840808.html
Copyright © 2011-2022 走看看