[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
The coincidence of linked lists is a fun issue. The original question is as follows: if there are two linked lists, how can we determine whether these two linked lists overlap? It doesn't matter when the linked list overlaps. The key is to determine whether the linked list is overlapped. What exactly is the solution?
The simplest way is to check whether the two have in common. Then, you can judge in sequence.
int find_node_in_link(LINK_NODE* pLink, LINK_NODE* pNode){while(pLink){if(pLink == pNode)return 1;pLink = pLink->next;}return 0;}STATUS find_if_link_merge(LINK_NODE* pLinkOne, LINK_NODE* pLinkTwo){LINK_NODE* pHead;if(NULL == pLinkOne || NULL == pLinkTwo)return FALSE;pHead = pLinkTwo;while(pHead){if(find_node_in_link(pLinkOne, pHead))return TRUE;pHead = pHead->next;}return FALSE;}
Another method is the counting method. Since the linked list overlaps somewhere, the number of accesses to this point is 2, so we can traverse the two linked lists in sequence, check whether the Count value of the node is 2.
typedef struct _LINK_NODE{int data;int count;struct _LINK_NODE* next;}LINK_NODE;void process_all_link_node(LINK_NODE* pNode){assert(NULL != pNode);while(pNode){pNode->count ++;pNode = pNode->next;}}
From the counting method, we can find that if the two linked lists overlap, their last node must be the same, so we only need to judge whether the last node is the same.
STATUS find_if_link_merge(LINK_NODE* pLinkOne, LINK_NODE* pLinkTwo){assert(NULL != pLinkOne && NULL != pLinkTwo);while(pLinkOne->next) pLinkOne = pLinkOne->next;while(pLinkTwo->next) pLinkTwo = pLinkTwo->next;return (pLinkOne == pLinkTwo) ? TRUE : FALSE;}
Summary:
1) Although the same linked list is simple, different answers can be provided from different perspectives;
2) This topic is from the beauty of programming. If you are interested in the solution, you can refer to the beauty of programming.