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.
  • 统计长度,减少内存空间
  1. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
  2. if(headA == NULL) return NULL;
  3. if(headB == NULL) return NULL;
  4. int lenA = 1;
  5. int lenB = 1;
  6. ListNode *pA = headA;
  7. ListNode *pB = headB;
  8. while(pA->next != NULL) {
  9. lenA++;
  10. pA=pA->next;
  11. }
  12. while(pB->next!=NULL) {
  13. lenB++;
  14. pB=pB->next;
  15. }
  16. if(pA!=pB) return NULL;
  17. int len = max(lenA,lenB) - min(lenA,lenB);
  18. pA = headA;
  19. pB = headB;
  20. if(lenA>lenB) {
  21. while(len>0) {
  22. pA = pA->next;
  23. len--;
  24. }
  25. } else if(lenB > lenA){
  26. while(len>0) {
  27. pB = pB -> next;
  28. len--;
  29. }
  30. }
  31. while(pA!=pB) {
  32. pA = pA->next;
  33. pB = pB ->next;
  34. }
  35. return pA;
  36. }
posted @ 2014-12-16 15:02  purejade  阅读(111)  评论(0)    收藏  举报