160. 两个链表的相交点 Intersection of Two Linked Lists

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.
题意:找出两个两个链表的相交点
解法:先算出两个链表的长度,同时遍历两个链表,较短的链表从位于Math.Abs(countA - countB)的节点开始遍历,直到两个指针指向的节点相同
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * public int val;
  5. * public ListNode next;
  6. * public ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
  11. int countA = GetCount(headA);
  12. int countB = GetCount(headB);
  13. int offset = Math.Abs(countA - countB);
  14. if (countA > countB) {
  15. headA = GetIndex(headA, offset);
  16. } else {
  17. headB = GetIndex(headB, offset);
  18. }
  19. while (headA != null && headB!=null) {
  20. if (headA.GetHashCode() == headB.GetHashCode()) {
  21. return headA;
  22. } else {
  23. headA = headA.next;
  24. headB = headB.next;
  25. }
  26. }
  27. return null;
  28. }
  29. public ListNode GetIndex(ListNode head,int index) {
  30. int count = 0;
  31. ListNode node = head;
  32. while (node != null) {
  33. if (count == index) {
  34. return node;
  35. } else {
  36. count++;
  37. node = node.next;
  38. }
  39. }
  40. return null;
  41. }
  42. public int GetCount(ListNode head) {
  43. int count = 0;
  44. ListNode node = head;
  45. while (node != null) {
  46. count++;
  47. node = node.next;
  48. }
  49. return count;
  50. }
  51. }








posted @ 2017-04-19 00:07  xiejunzhao  阅读(159)  评论(0编辑  收藏  举报