面试题37 两个链表的第一个公共结点
题目描述
输入两个链表,找出它们的第一个公共结点。
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) { 12 if (pHead1 == NULL || pHead2 == NULL) 13 return NULL; 14 ListNode *p1 = pHead1, *p2 = pHead2; 15 int l1 = 0, l2 = 0; 16 while(p1){ 17 l1++; 18 p1 = p1->next; 19 } 20 21 while(p2){ 22 l2++; 23 p2 = p2->next; 24 } 25 26 int n = l1 - l2; 27 p1 = pHead1; p2 = pHead2; 28 if (l2 > l1){ 29 p1 = pHead2; 30 p2 = pHead1; 31 n = l2 - l1; 32 } 33 for (int i = 0; i < n; i++) 34 p1 = p1->next; 35 while (p1 != NULL && p2 != NULL && p1 != p2){ 36 p1 = p1->next; 37 p2 = p2->next; 38 } 39 ListNode *p = p1; 40 return p; 41 } 42 };
1 class Solution { 2 public: 3 int Merge(vector<int> &A, int p, int q, int r) 4 { 5 int count = 0; 6 7 vector<int> B; 8 vector<int> C; 9 10 for (int i = p; i <= q; i++) 11 { 12 B.push_back(A[i]); 13 } 14 for (int i = q + 1; i <= r; i++) 15 { 16 C.push_back(A[i]); 17 } 18 19 int m = B.size() - 1, n = C.size() - 1; 20 for (int i = r; i >= p; i--) 21 { 22 if (m == -1 && n != -1) 23 { 24 while (n != -1) 25 { 26 A[i] = C[n]; 27 i--; 28 n--; 29 } 30 break; 31 } 32 if (m != -1 && n == -1) 33 { 34 while (m != -1) 35 { 36 A[i] = B[m]; 37 i--; 38 m--; 39 } 40 break; 41 } 42 if (B[m] <= C[n]) 43 { 44 A[i] = C[n]; 45 n--; 46 } 47 else 48 { 49 count += n + 1; 50 A[i] = B[m]; 51 m--; 52 } 53 } 54 return count; 55 } 56 57 int MergeSort(vector<int> &A, int p, int r) 58 { 59 if (p == r) 60 return 0; 61 int q = (p + r) / 2; 62 int left = MergeSort(A, p, q); 63 int right = MergeSort(A, q + 1, r); 64 return left + right + Merge(A, p, q, r); 65 } 66 67 int InversePairs(vector<int> &data) { 68 if (data.size() == 0) 69 return 0; 70 return MergeSort(data, 0, data.size() - 1); 71 } 72 };