LeetCode 160. Intersection of Two Linked Lists

来源:互联网 发布:27岁转行做java 编辑:程序博客网 时间:2024/06/04 17:41

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2                   ↘                     c1 → c2 → c3                   ↗            B:     b1 → b2 → b3

begin to intersect at node c1.


Notes:

  • 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.

解题思路:分为如下几种情况:

1)两个list中有一个为空,返回null;

2)两个list都不为空,则又分为两种情况:

      1)一个list的完全包含了另一个list,也就是说一个list的head在另一个list里

      2)一个list与另一个list交叉,各自的head不相交

     对于上述两种情况,可以把第一种情况看作是第二种情况的特例,所以主要考虑第二种情况。先计算两个list的节点个数,令较长list的指针先走两个list节点总长的差值,然后再让两个指针同时向前走,判断是否相遇,对于第一种情况,可以在计算list节点个数时,进行判断

public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA==null|| headB==null){            return null;        }else{            int counta=0,countb=0;            ListNode qa=headA,qb=headB;            while(qa!=null && qa!=headB){  //headB是headA的一部分                counta++;                qa=qa.next;                           }            if(qa!=null){                return headB;            }            while(qb!=null && qb!=headA){       //headA是headB的一部分                countb++;                qb=qb.next;            }            if(qb!=null){                return headA;            }                int i=0,counterr=Math.abs(counta-countb);                if(counta<countb){      //使qa始终指向较长链表                    qa=headB;                    qb=headA;                }else{                    qa=headA;                    qb=headB;                }                while(i<counterr){                        qa=qa.next;                    i++;                }                while(qb!=null && qa!=qb){                    qa=qa.next;                    qb=qb.next;                }                if(qa!=null){                    return qa;                }else{                    return null;                }                                    }    }}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 孩子屁股长了湿疹怎么办 宝宝发脾气摔东西躺地上怎么办 生气拿棍子打了孩子怎么办 小宝宝被蚊虫咬了怎么办 小宝宝被蚊子咬了怎么办 衣架打小孩淤青怎么办 1岁宝宝有痰咳嗽怎么办 1岁宝宝咳嗽有痰怎么办 孩子爱动手打家长怎么办 不小心有了孩子该怎么办 2岁多宝宝干咳怎么办 2岁宝宝咳嗽无痰怎么办 打了孩子后悔了怎么办 12小孩脾气很犟怎么办 被学生气着了怎么办 1岁宝宝轻微咳嗽怎么办 4岁宝宝突然呕吐怎么办 4岁儿童突然呕吐怎么办 四岁儿童90身高怎么办 24个月宝宝缺钙怎么办 狗狗总是要人陪着玩怎么办 成年了还是很皮怎么办 三岁儿子太调皮怎么办 10个月宝宝粘人怎么办 6个月宝宝粘人怎么办 9个月宝宝偏矮怎么办 1岁宝宝粘人爱哭怎么办 宝宝2岁半胆小怎么办 5岁宝宝超级粘人怎么办 狗狗吃饭要人喂怎么办 十个月宝宝认人怎么办 一岁宝宝粘人怎么办 9个月宝宝粘妈妈怎么办 一岁的宝宝呕吐怎么办 宝宝一岁八个月太粘人了怎么办 六个月的宝宝好粘人怎么办 两岁半宝宝说话突然结巴了怎么办 1岁宝宝突然呕吐怎么办 宝宝吃坏了呕吐怎么办 1岁宝宝吃饭爱玩怎么办 7岁儿童半夜呕吐怎么办