zoukankan      html  css  js  c++  java
  • [Algorithm] Find merge point of two linked list

    Assume we have two linked list, we want to find a point in each list, from which all the the nodes share the same value in both list. Then we call this point is "merge point".

     In the iamge, the merge point shoud be Node(7). 

      // Link A length 4, Link B length 5
      // All the node after the merge point should be the same
      // based on that, we can make sure that the merge point should
      // happens in range [x, c] or [y, c], it is not possible to happen at z
      // A      x - x - c - c
      // B  z - y - y - c - c
    function Node(val) {
      return {
        val,
        next: null
      };
    }
    
    function Link() {
      return {
        head: null,
        tail: null,
        length: 0,
        add(val) {
          const newNode = new Node(val);
    
          if (this.length === 0) {
            this.head = newNode;
            this.tail = newNode;
            this.tail.next = null;
          } else {
            let temp = this.tail;
            this.tail = newNode;
            temp.next = this.tail;
          }
    
          this.length++;
        }
      };
    }
    
     // O ( m + n ), Space: O(1)
    function findMergePoint(a, b) {
      // Link A length 4, Link B length 5
      // All the node after the merge point should be the same
      // based on that, we can make sure that the merge point should
      // happens in range [x, c] or [y, c], it is not possible to happen at z
      // A      x - x - c - c
      // B  z - y - y - c - c
      let diff, headA = a.head, headB = b.head;
      if (a.length > b.length) { // O(1)
        diff = a.length - b.length; 
        [a, b] = [b, a];
      } else {
        diff = b.length - a.length;
      }
    
      // reach +diff step for longer 
      for (let i = 0; i < diff; i++) {
        headB = headB.next; // O(m)
      }
    
      while (headA != null && headB.val != null ) { // O(n)
        if (headA.val === headB.val) {
          return headA;
        }
    
        headA = headA.next;
        headB = headB.next;
      } 
    
      return null;
    }
    
    const lA = new Link();
    lA.add(4);
    lA.add(6);
    lA.add(7);
    lA.add(1);
    
    const lB = new Link();
    lB.add(9);
    lB.add(3);
    lB.add(5);
    lB.add(7);
    lB.add(1);
    
    console.log(findMergePoint(lA, lB)); // Object {val: 7, next: Object}
  • 相关阅读:
    [哈工大操作系统]一、环境配置
    [算法笔记]带权并查集
    C++:Reference to non-static member function must be called
    [算法笔记]并查集
    C++:string.size()比较问题
    [算法笔记]二分总结
    【LeetCode每日一题】2020.10.15 116. 填充每个节点的下一个右侧节点指针
    1Manjaro的安装
    【《你不知道的JS(中卷②)》】一、 异步:现在与未来
    【LeetCode每日一题】2020.7.14 120. 三角形最小路径和
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10650273.html
Copyright © 2011-2022 走看看