[Leetcode 160] Intersection of Linked Lists

Source: Internet
Author: User

Title Link: intersection-of-two-linked-lists


/** * Write A program to find the node at which the intersection of the singly linked lists begins.                               For example, the following, linked lists:a: A1→a2 c1→c2→c3 B:b1→b2→b3begin to intersect at node C1. Notes:if The linked lists has no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there is 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 Intersectionoftwolinkedlists {public class ListNode {int val;      ListNode Next;          ListNode (int x) {val = x;      next = null; }}//42/42 test Cases passed.//status:accepted//runtime:327 ms//submitted:3 minutes ago//Time complexity O (m+n) space complexity O (1)///problem-solving ideas://1. The number of nodes that count the two linked lists is first traversed separately. 2. Then traverse again, this time the list of the larger number of nodes to go first | two-node difference | step//3. At the same time, determine whether the nodes are equal public ListNodeGetintersectionnode (ListNode Heada, ListNode headb) {int NumA = 0;//a List of nodes int numB = number of nodes 0;//b list listn    Ode CurA = Heada;    ListNode CurB = headb; while (CurA! = null) {Numa++;cura = Cura.next;} while (CurB! = null) {numb++;curb = Curb.next;} CurA = Heada;curb = Headb;while (NumA < NumB) {CurB = Curb.next;numb--;}    while (NumA > NumB) {curA = Cura.next;numa--;}    while (CurA! = CurB) {CurA = Cura.next;curb = Curb.next;}        return CurA; }public static void Main (string[] args) {//TODO auto-generated method stub}}


[Leetcode 160] Intersection of Linked Lists

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.