• LeetCode(160): Intersection of Two Linked Lists


    Intersection of Two Linked Lists:

    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.

    题意:找出给定的两个链表,链表开始相交的交点。

    思路:先分别遍历两个链表获取两个链表的长度,len1和len1,并定义两个指针p和q,如果len1==len2则两个指针分别同时指向链表的首节点;如果len1>len2或len1<len2,则指针p或q,指向第|len1-len2|个节点,然后在进行判断。

    代码:

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
             int a_len = 0;
             int b_len = 0;
             ListNode p = headA;
             ListNode q = headB;
             while(p!=null){
                 a_len++;
                 p=p.next;
             }
             p = headB;
             while(p!=null){
                 b_len++;
                 p=p.next;
             }
             if(a_len==0||b_len==0){
                 return null;
             }
             p = headA;
             q = headB;
             int sub_len = a_len - b_len;
             if(sub_len!=0){
                 if(sub_len>0){
                     while(sub_len>0){
                         p = p.next;
                         sub_len --;
                     }
                 }else{
                     sub_len = -1*sub_len;
                     while(sub_len>0){
                         q= q.next;
                         sub_len--;
                     }
                 }
             }
             while(p!=null&&q!=null){
                 if(p==q){
                     return p;
                 }else{
                     p = p.next;
                     q = q.next;
                 }
             }
             return null;
        }
  • 相关阅读:
    FreeBSD10下的MySQL5.5配置安装
    TCP Wrappers
    SNAT技术
    子网掩码, 网段主机数计算
    functools wraps
    数据库引擎
    restframework
    Python使用asyncio+aiohttp异步爬取猫眼电影专业版
    Linux 总结
    Nginx日志管理
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5131454.html
Copyright © 2020-2023  润新知