标签:san span time use top add tom etc 指针
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:
null.
/*** Definition for singly-linked list.* public class ListNode {* public int val;* public ListNode next;* public ListNode(int x) { val = x; }* }*/public class Solution {public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {int countA = GetCount(headA);int countB = GetCount(headB);int offset = Math.Abs(countA - countB);if (countA > countB) {headA = GetIndex(headA, offset);} else {headB = GetIndex(headB, offset);}while (headA != null && headB!=null) {if (headA.GetHashCode() == headB.GetHashCode()) {return headA;} else {headA = headA.next;headB = headB.next;}}return null;}public ListNode GetIndex(ListNode head,int index) {int count = 0;ListNode node = head;while (node != null) {if (count == index) {return node;} else {count++;node = node.next;}}return null;}public int GetCount(ListNode head) {int count = 0;ListNode node = head;while (node != null) {count++;node = node.next;}return count;}}
160. 两个链表的相交点 Intersection of Two Linked Lists
标签:san span time use top add tom etc 指针
原文地址:http://www.cnblogs.com/xiejunzhao/p/9275c6a968a1b6c456e817c14c6d3ccf.html