zoukankan      html  css  js  c++  java
  • LeetCode——Intersection of Two Linked Lists

    Description:

    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.

    求两个链表的相交的部分

    /**
     * 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) {
            if(headA==null || headB==null)
                return null;
            ListNode aNode = headA;
            ListNode bNode = headB;
            int aLen = 0, bLen = 0;
            while(aNode != null) {
                aLen ++;
                aNode = aNode.next;
            }
            while(bNode != null) {
                bLen ++;
                bNode = bNode.next;
            }
            if(aNode != bNode) 
                return null;
            if(aLen > bLen) {
                 for(int i = 0; i < aLen-bLen; i++)
                    headA = headA.next;
            }
            else if(aLen < bLen) {
                for(int i=0; i<bLen-aLen; i++)
                    headB = headB.next;
            }
            while(headA != headB) {
                headA = headA.next;
                headB = headB.next;
            }
            return headA;
        }
    }
    
  • 相关阅读:
    Conv2 GPU加速(有代码有图有真相)
    OpenACC指令适不适合我的程序吗?
    MongoDBHelper
    Js事件 事件绑定
    xslt元素 applyimports
    博客成立,开启一段追逐之旅,留个小小的纪念 ^^
    函数
    C语言基本特性
    预处理
    数组
  • 原文地址:https://www.cnblogs.com/wxisme/p/4589905.html
Copyright © 2011-2022 走看看