题目要求:
两个无环单向链表,找出它们的第一个公共结点。
参考资料:剑指offer第37题。
题目分析:
代码实现:
#include <iostream> using namespace std; typedef struct ListNode { struct ListNode *next; int data; }ListNode; void InitList(ListNode **head1,ListNode **head2); ListNode *FindFirstCommonNode(ListNode *pHead1,ListNode *pHead2); void PrintList(ListNode *h); int main(void) { ListNode *h1 = NULL,*h2 = NULL; InitList(&h1,&h2); cout << "h1为:"; PrintList(h1); cout << "h2为:"; PrintList(h2); ListNode *pFirstCommonNode = FindFirstCommonNode(h1,h2); if(pFirstCommonNode) cout << "第一个公共结点的值为:" << pFirstCommonNode->data << endl; else cout <<"没有公共结点" << endl; return 0; } void PrintList(ListNode *h) { while(h!=NULL) { cout << h->data << " "; h = h->next; } cout << endl; } unsigned int GetListLength(ListNode *pHead) { unsigned int nLen = 0; ListNode *pNode = pHead; while(pNode != NULL) { ++nLen; pNode = pNode->next; } return nLen; } ListNode *FindFirstCommonNode(ListNode *pHead1,ListNode *pHead2) { if(pHead1==NULL || pHead2==NULL) return NULL; unsigned int len1 = GetListLength(pHead1); unsigned int len2 = GetListLength(pHead2); int lenDif = len1-len2; ListNode *pListHeadLong = pHead1; ListNode *pListHeadShort = pHead2; if(len1<len2) { pListHeadLong = pHead2; pListHeadShort = pHead1; lenDif = len2-len1; } for(int i = 0;i<lenDif;i++) pListHeadLong = pListHeadLong->next; while((pListHeadLong!=NULL) && (pListHeadShort!=NULL) && (pListHeadLong!=pListHeadShort)) { pListHeadLong = pListHeadLong->next; pListHeadShort = pListHeadShort->next; } return pListHeadLong; } //head1:1-->5-->9-->NULL //head2:2-->4-->10-->5-->9-->NULL void InitList(ListNode **head1,ListNode **head2) { ListNode *tmp = new ListNode,*store; tmp->data = 1; *head1 = tmp; tmp = new ListNode; tmp->data = 5; store = tmp; (*head1)->next = tmp; ListNode *tmp1 = new ListNode; tmp1->data = 9; tmp1->next = NULL; tmp->next = tmp1; tmp = new ListNode; tmp->data = 2; *head2 = tmp; tmp = new ListNode; tmp->data = 4; (*head2)->next = tmp; tmp1 = new ListNode; tmp1->data = 10; tmp1->next = store; tmp->next = tmp1; }