标签:
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
.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
这道题是说有两个链表在某一点就合二为一,找到这个点。
所以,正常的只要按序遍历整个单链表即可。
我们注意到链表长度可能不同,所以可以让长度长的链表先走两个链表长度差的长度,再开始比较每个元素。
还有如果最后一个节点不同那个按照题意,则两个链表没有相交的节点
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 int lenA = 1; 13 int lenB = 1; 14 ListNode *pa = headA; 15 ListNode *pb = headB; 16 if(headA == NULL ||headB == NULL) return NULL; 17 while(pa->next) 18 { 19 lenA++; 20 pa = pa->next; 21 } 22 while(pb->next) 23 { 24 lenB++; 25 pb = pb->next; 26 } 27 if(pa != pb) return NULL; 28 if(lenA > lenB) 29 { 30 for(int i =0;i<lenA-lenB;i++) 31 { 32 headA = headA->next; 33 } 34 } 35 else if(lenB > lenA) 36 { 37 for(int i = 0;i < lenB-lenA;i++) 38 { 39 headB = headB->next; 40 } 41 } 42 43 while(headA && headB) 44 { 45 if(headA != headB) 46 { 47 headA=headA->next; 48 headB=headB->next; 49 } 50 else 51 return headA; 52 } 53 54 } 55 };
Intersection of Two Linked Lists
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4584976.html