160. Intersection of Two Linked Lists

来源:互联网 发布:奥迪工程师软件 编辑:程序博客网 时间:2024/06/06 19:42

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.

直接记住就可以,没什么技巧!

java

/** * 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 = Length(headA);        int lenB = Lenght(headB);        while (lenA > lenB) {            headA = headA.next;            lenA--;        }        while (lenA < lenB) {            headB = headB.next;            lenB--;        }        while (headA != headB) {            headA = headA.next;            headB = headB.next;        }        return headA;    }    private int Length(ListNode head) {        int num = 0;        while (head != null) {            head = head.next;            num++;        }        return num;    }}

python

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def getIntersectionNode(self, headA, headB):        """        :type head1, head1: ListNode        :rtype: ListNode        """        if headA is None or headB is None:            return None        lenA = self.length(headA)        lenB = self.length(headB)        while lenA > lenB:            headA = headA.next            lenA -= 1        while lenA < lenB:            headB = headB.next            lenB -= 1        while headA is not headB:            headA = headA.next            headB = headB.next        return headA            def length(self, head):        num = 0        while head is not None:            head = head.next            num += 1        return num