• [leetCode]160.相交链表


    在这里插入图片描述

    暴力法

    每次从一个链表中取出一个结点,将该结点与另一个链表所有结点比对如果相等则返回当前结点。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode pA = headA;
            ListNode pB = headB;
            while(pA!=null){
                while(pB!=null){
                    if(pA == pB) return pA;
                    pB = pB.next;
                }
                pA = pA.next;
                pB = headB;
            }
            return null;
        }
    }
    

    哈希表

    将一个链表的元素加入哈希表,遍历另一个链表判断其结点是否存在于哈希表中。

    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            HashSet<ListNode> set = new HashSet<>();
            while(headA!=null && !set.contains(headA)){
                set.add(headA);
                headA = headA.next;
            }
            while(headB != null){
                if(set.contains(headB)) return headB;
                headB = headB.next;
            }
            return null;
        }
    }
    

    双指针

    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode pA = headA;
            ListNode pB = headB;
            if(pA == null ||  pB == null) return null;
            while(pA !=null || pB != null){
                if(pA == null) pA = headB;
                else if(pB == null) pB = headA;
                if(pA == pB) return pB;
                pA = pA.next;
                pB = pB.next;
            }
            return null;
        }
    }
    
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA == null ||  headB == null) return null;
            ListNode pA = headA;
            ListNode pB = headB;
            while(pA != pB){
                pA = (pA == null ? headB : pA.next);
                pB = (pB == null ? headA : pB.next);
            }
            return pB;
        }
    }
    
  • 相关阅读:
    Lesson 1#05-用户交互和注释
    Lesson 1#04-变量与常量
    Lesson 1#03-Python安装与Hello Python World
    elementUI 表格之合并同类项(包括行和列)
    elementUI 表格之表头合并
    VSCode关于编译scss的插件
    elementUI中的级联选择器,默认赋值不起作用
    highcharts中的环形图
    highcharts中的折线图
    highcharts中的仪表盘样式
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859998.html
Copyright © 2020-2023  润新知