劍指offer 36:兩個連結串列的第一個公共節點
阿新 • • 發佈:2018-12-30
#include <iostream> struct ListNode { public: int val; struct ListNode *next; }; using namespace std; class solution { public: //36 找到兩個連結串列的第一個公共節點 //讓長的一個連結串列先走,實現右對齊 ListNode* FindFirstCommonNode(ListNode *leftHead ,ListNode *rightHead) { ListNode *left = leftHead; ListNode *right = rightHead; int leftLength = 0; int rightLength = 0; leftLength = GetListLength(left); rightLength = GetListLength(right); int length = 0; if (leftLength < rightLength) { length = rightLength - leftLength; while (right != NULL && length > 0) { right = right->next; length--; } }//右先走 else { length = leftLength - rightLength; while(left != NULL && length > 0) { left = left->next; length--; } }//左先走 while (left != NULL && right !=NULL) { if (left == right) { break; } left = left->next; right = right->next; }//一起走,直到相遇 return ((left == right) ? left : NULL); } int GetListLength(ListNode *head) { ListNode *node = head; int length = 0; while (node != NULL) { length++; node = node->next; } return length; } //遍歷 //拼接起來右對齊 //棧youduiqi //map ,hashmap }; int main() { ListNode common[2]; common[0].val = 8; common[0].next = &common[1]; common[1].val = 9; common[1].next = NULL; ListNode list[4]; list[0].val = 1; list[0].next = &list[1]; list[1].val = 2; list[1].next = &list[2]; list[2].val = 3; list[2].next = &list[3]; list[3].val = 4; list[3].next = &common[0]; ListNode list2[2]; list2[0].val = 5; list2[0].next = &list2[1]; list2[1].val = 6; list2[1].next = &common[0]; solution solu; ListNode *node = solu.FindFirstCommonNode(list, list2); while (node != NULL) { cout << node->val << endl; node = node->next; } return 0; }