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;
        }
    }
    
  • 相关阅读:
    1635:【例 5】Strange Way to Express Integers
    1633:【例 3】Sumdiv
    1632:【 例 2】[NOIP2012]同余方程
    1631:【例 1】青蛙的约会
    1629:聪明的燕姿
    1628:X-factor Chain
    1627:【例 3】最大公约数
    1626:【例 2】Hankson 的趣味题
    file_put_contens小trick
    billu b0x2靶机渗透
  • 原文地址:https://www.cnblogs.com/a1225234/p/11012629.html
Copyright © 2011-2022 走看看