160. Intersection of Two Linked Lists

来源:互联网 发布:nginx 视频服务器 编辑:程序博客网 时间:2024/05/15 00:23

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.


分析:因为其后面的元素都是一样的,先得出每个列表的长度,然后将长度长的往后移动直到其后面的长度和短的一样,然后逐渐判断和短的列表的元素是不是一样,不一样的话则都往后移一个。

时间复杂度:O(M)


/** * 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;        int lena=0;        int lenb=0;        ListNode temp=headA;        ListNode temp1=headB;        while(temp!=null){            lena++;            temp=temp.next;        }         while(temp1!=null){            lenb++;            temp1=temp1.next;        }        if(lena<lenb){            temp1=headB;            int i=lenb-lena;            while(i>0){                temp1=temp1.next;                i--;            }            temp=headA;        }else{            temp=headA;            int i=lena-lenb;            while(i>0){                temp=temp.next;                i--;            }            temp1=headB;        }        while(temp!=temp1){                temp=temp.next;                temp1=temp1.next;        }        return temp;    }}


0 0
原创粉丝点击