zoukankan      html  css  js  c++  java
  • [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;
        }
    }
    
  • 相关阅读:
    ORA-12543: TNS:destination host unreachable
    Visual Studio 2008 连接云端 visualstudio.com
    将博客搬至CSDN
    Shiro 系列笔记(一)
    Centos 6.7 安装jdk
    Centos service启动失败原因--权限问题
    form表单提交的ajax形式
    slf4j与mybatis结合显示sql
    Docker 部署 redis教程,附带部分小建议,防止踩坑
    Android中的EditText默认时不弹出软键盘的方法
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859998.html
Copyright © 2011-2022 走看看