首页 > 代码库 > leetcode 160: Intersection of Two Linked Lists

leetcode 160: Intersection of Two Linked Lists

Intersection of Two Linked Lists

Total Accepted: 8676 Total Submissions: 32571

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.

[分析]

解法一:
  第一遍循环,找出两个链表的长度差N
  第二遍循环,长链表先走N步,然后同时移动,判断是否有相同节点

解法二:

  链表到尾部后,跳到另一个链表的头部, 相遇点即为intersection points.

[注意事项]
NONE

[CODE]

  解法一:

/**
 * 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 p = headA;
        ListNode q = headB;
        int pcount = 0;
        int qcount = 0;
        while(p.next != null || q.next != null) {
            if(p == q) return p;
            if(p.next != null) p = p.next; else ++qcount;
            if(q.next != null) q = q.next; else ++pcount;
        }
        if(p != q) return null;
        p = headA;
        q = headB;
        while(pcount-- != 0) {
            p = p.next;
        }
        
        while(qcount-- != 0) {
            q = q.next;
        }
        
        while(p != q) {
            p = p.next;
            q = q.next;
        }
        return p;
    }
}


  解法二:

/**
 * 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 p = headA;
        ListNode q = headB;
        if(p == q) return p;        
        while(p!=null && q!=null) {
            p = p.next;
            q = q.next;
        }
        
        if(p==null) p = headB; else q = headA;
        
        while(p!=null && q!=null) {
            p = p.next;
            q = q.next;
        }

        if(p==null) p = headB; else q = headA;

        while(p!=null && q!=null) {
            if(p==q) return p;
            p = p.next;
            q = q.next;
        }
        return null;
    }
}


leetcode 160: Intersection of Two Linked Lists