zoukankan      html  css  js  c++  java
  • 【剑指offer】链表第一个公共子结点

    *思路: 先求得两个链表的长度,然后得到长度差diff,再先遍历长链表diff步后,再同时遍历两个链表并比较对象指针。

     1 /*
     2 public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }*/
    10 public class Solution {
    11     public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
    12       if(pHead1==null||pHead2==null) 
    13         {return null;}
    14       ListNode temp1 = pHead1;
    15       ListNode temp2 = pHead2;
    16       int length1=0;
    17       int length2=0;
    18       while(temp1!=null){
    19           length1++;
    20           temp1 = temp1.next;
    21       }
    22       while(temp2!=null){
    23           length2++;
    24           temp2 = temp2.next;
    25       }
    26       int diff= Math.abs(length1-length2);
    27       if(length1>=length2){
    28           for(int i=0; i<diff; i++){
    29               pHead1 = pHead1.next;
    30           }
    31       }else{
    32           for(int i=0; i<diff; i++){
    33               pHead2 = pHead2.next;
    34           }
    35       }
    36       while(pHead1!=pHead2){
    37           pHead1 = pHead1.next;
    38           pHead2 = pHead2.next;
    39       }
    40 
    41       return pHead1;
    42       
    43     }
    44 }
  • 相关阅读:
    Android随笔
    Android随笔
    Android随笔
    Android随笔
    Android随笔
    Android随笔
    Android随笔
    Android随笔
    Android随笔
    Codeforces Round #551题解
  • 原文地址:https://www.cnblogs.com/singular/p/10192277.html
Copyright © 2011-2022 走看看