撰寫一個程式,找到兩個單鏈表相交的起始節點,如下面的兩個鏈表:




1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 set<ListNode*> node_set; 5 while (headA) { 6 node_set.insert(headA); 7 headA = headA->next; 8 } 9 while (headB) {10 if (node_set.find(headB) != node_set.end()) { //find()沒找到,回傳 end()11 return headB;12 }13 headB = headB->next;14 }15 return NULL;16 }17 };
思路 2計算鏈表長度和長度之差
將長鏈表指標移動到和短鏈表對齊
headA 和 headB 同時移動,直到兩指標指向同一節點
1 class Solution { 2 public: 3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 int list_A_len = getListLength(headA); 5 int list_B_len = getListLength(headB); 6 if (list_A_len > list_B_len) { 7 headA = forwardLongList(headA, list_A_len, list_B_len); 8 } else { 9 headB = forwardLongList(headB, list_B_len, list_A_len);10 }11 while (headA && headB) {12 if (headA == headB) {13 return headA;14 }15 headA = headA->next;16 headB = headB->next;17 }18 return NULL;19 }20 private:21 //計算鏈表長度22 int getListLength(ListNode* head) {23 int len = 0;24 while (head) {25 ++len;26 head = head->next;27 }28 return len;29 }30 31 //將長鏈表指標向后移動,回傳對齊后的位置32 ListNode* forwardLongList(ListNode* long_head, int long_len, int short_len) {33 int delta = long_len - short_len;34 while (long_head && delta) {35 long_head = long_head->next;36 --delta;37 }38 return long_head;39 }40 };
測驗

1 int main(int argc, const char * argv[]) { 2 ListNode a1(1); 3 ListNode a2(2); 4 ListNode b1(3); 5 ListNode b2(4); 6 ListNode b3(5); 7 ListNode c1(6); 8 ListNode c2(7); 9 ListNode c3(8);10 a1.next = &a2;11 a2.next = &c1;12 c1.next = &c2;13 c2.next = &c3;14 b1.next = &b2;15 b2.next = &b3;16 b3.next = &c1;17 18 Solution solve;19 ListNode *result = solve.getIntersectionNode(&a1, &b1);20 cout <<result->val;21 22 return 0;23 }View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/87994.html
標籤:C++

