【leetcode】【160】Intersection of Two Linked Lists

来源:互联网 发布:c语言指针视频教程 编辑:程序博客网 时间:2024/06/01 15:07

一、问题描述

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.

二、问题分析

无非就是遍历两个链表,如果遍历两个链表的指针相同就return。因为两个链表的长度可能不一样,所以有两种方案:①分别计算两个链表的长度,然后遍历②正常遍历,遍历到尾的时候就将指针指向另一个链表,当两个指针同时为空的时候说明同时到尾了。具体的看代码。

三、Java AC代码

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA == null || headB == null){return null;}ListNode p = headA;ListNode q = headB;int count = 0;while(p!=null || q!=null){if (q == p) {return p;}p = p.next;q = q.next;if(p==null && q==null){    return null;}if (p == null) {count++;p = headB;}if (q == null) {count++;q = headA;}}return null;    }
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA == null || headB == null){return null;}ListNode p = headA;ListNode q = headB;int lena = 0;int lenb = 0;while(p!=null){lena++;p = p.next;}while(q!=null){lenb++;q = q.next;}p = headA;q = headB;for(int i=Math.abs(lena-lenb);i>0;i--){if (lena>lenb) {p = p.next;}else {q = q.next;}}while(q!=null&& q!=null){if (p == q) {return p;}else {p = p.next;q = q.next;}}return null;    }



0 0
原创粉丝点击