题目:输入两个链表,找出它们的第一个公共结点。
O(m+n)
思路:首先遍历两个链表得到它们的长度,就能知道哪个链表比较长,以及长的链表比短的链表多几个结点。在第二次遍历的时候,在较长的链表上先走若干步,接着再同时在两个链表上遍历,找到的第一个相同的结点就是它们的第一个公共结点。
1 struct ListNode 2 { 3 int val; 4 ListNode * next; 5 }; 6 7 int GetListLength( ListNode * head ) 8 { 9 int length = 0; 10 ListNode *tmp = head; 11 while( !tmp ) 12 { 13 ++length; 14 tmp = tmp->next; 15 } 16 return length; 17 } 18 19 ListNode * FindFirstCommonNode( ListNode * head1, ListNode * head2 ) 20 { 21 ListNode * result = NULL; 22 23 if( head1 == NULL || head2 == NULL ) 24 { 25 return result; 26 } 27 28 int Lhead1 = GetListLength( head1 ); 29 int Lhead2 = GetListLength( head2 ); 30 int LenD = Lhead1 - Lhead2; 31 ListNode * LongList = head1; 32 ListNode * ShortList = head2; 33 34 if( LenD < 0 ) 35 { 36 LongList = head2; 37 ShortList = head1; 38 LenD = -LenD; 39 } 40 41 for( int i = 0; i < LenD; ++i ) 42 { 43 LongList = LongList->next; 44 } 45 46 while( LongList != NULL && ShortList != NULL && LongList != ShortList ) 47 { 48 LongList = LongList->next; 49 ShortList = ShortList->next; 50 } 51 52 if( LongList == ShortList ) //判断是否有公共点 53 result = LongList; 54 55 return result; 56 }
来源:https://www.cnblogs.com/litana/p/3217556.html