首页 > 其他 > 详细

LeetCode 链表 160. Intersection of Two Linked Lists

时间:2020-03-02 23:02:05      阅读:73      评论:0      收藏:0      [点我收藏+]

LeetCode 链表 160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.
https://assets.leetcode.com/uploads/2018/12/13/160_statement.png
begin to intersect at node c1.

Notice:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

代码:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) return null;
        int depthA = depth(headA);
        int depthB = depth(headB);
        ListNode pA = headA;
        ListNode pB = headB;
        if(depthA >= depthB){
            while(depthA > depthB){
                pA = pA.next;
                depthA--;
            }                
        }else{
            while(depthB > depthA){
                pB = pB.next;
                depthB--;
            }                
        }
        while(pA != null && pB != null){
            if(pA==pB) break;
            pA = pA.next;
            pB = pB.next;
        }
        return pA;
    }
    private int depth(ListNode head){
        int dep = 0;
        ListNode cur = head;
        while(cur != null){
            dep++;
            cur = cur.next;
        }
        return dep;
    }
}

注意:
书写代码自己要规范,不然容易自己犯一些很傻的错误

LeetCode 链表 160. Intersection of Two Linked Lists

原文:https://www.cnblogs.com/muche-moqi/p/12398496.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!