zoukankan      html  css  js  c++  java
  • 输入两个链表,找出它们的第一个公共结点

    import java.util.*;
    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            ListNode head = pHead1;
            Set<ListNode> res= new HashSet<ListNode>();
            while(head!=null){
                res.add(head);
                head = head.next;
            }
            head = pHead2;
            while(head!=null){
                if(res.contains(head))
                    break;
                head = head.next;
            }
            return head;
        }
    }
    

    求出两个链表长度差

    import java.util.*;
    /*
    public class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }*/
    public class Solution {
        public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            int len1=0,len2=0;
            ListNode head = pHead1;
            while(head!=null){
                len1++;
                head = head.next;
            }
            head = pHead2;
            while(head!=null){
                len2++;
                head = head.next;
            }
            ListNode maxList=null,minList=null;
            int lenc = Math.abs(len1-len2);
            if(len1>=len2){
                maxList = pHead1;
                minList = pHead2;
            }
            if(len2>len1){
                maxList = pHead2;
                minList = pHead1;
            }
            while(lenc!=0){
                maxList = maxList.next;
                lenc--;
            }
            while(maxList!=minList){
                maxList = maxList.next;
                minList = minList.next;
            }
            return maxList;
        }
    }
    
  • 相关阅读:
    php 克隆和引用类
    php 抽象类、接口和构析方法
    php 面向对象之继承、多态和静态方法
    php封装练习
    php 面向对象之封装
    php 简单操作数据库
    php 练习
    用php输入表格内容
    php 指针遍历、预定义数组和常用函数
    php 数组定义、取值和遍历
  • 原文地址:https://www.cnblogs.com/a1225234/p/11012629.html
Copyright © 2011-2022 走看看