码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-04-19 00:23:46      阅读:159      评论:0      收藏:0      [点我收藏+]

标签: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:

  • 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. }








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

标签:san   span   time   use   top   add   tom   etc   指针   

原文地址:http://www.cnblogs.com/xiejunzhao/p/9275c6a968a1b6c456e817c14c6d3ccf.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!