编程之美-判断两个链表是否相交方法整理
生活随笔
收集整理的這篇文章主要介紹了
编程之美-判断两个链表是否相交方法整理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【試題描述】
記
N = length(h1)
M = length(h2)
方法一:暴力搜索,時間復雜度為O(N*M)
方法二:時間復雜度為O(N+M)
方法三:
方法四:時間復雜度為O(N+M)
方法五:
typedef struct Node {int data;struct Node *next; }Node;Node* FindIntersection(Node *pHead1, Node *pHead2) {if(NULL == pHead1 || NULL == pHead2){return NULL;}Node *pCurrent1, *pCurrent2;pCurrent1 = pHead1;pCurrent2 = pHead2;int len1 = 0, int len2 =0;int diff = 0;while(NULL != pCurrent1){pCurrent1 = pCurrent1 -> next;len1++;}while(NULL != pCurrent2){pCurrent2 = pCurrent2 -> next;len2++;}if(pCurrent1 != pCurrent2) return NULL;diff = abs(len1 - len2);if(len1 > len2){ pCurrent1 = pHead1;pCurrent2 = pHead2;}else{pCurrent1 = pHead2;pCurrent2 = pHead1;}for(int i=0; i<diff; i++)pCurrent1 = pCurrent1->next;while(pCurrent1 != pCurrent2){pCurrent1 = pCurrent1->next;pCurrent2 = pCurrent2->next;}return pCurrent1; }總結
以上是生活随笔為你收集整理的编程之美-判断两个链表是否相交方法整理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编程之美-最短摘要的生成方法整理
- 下一篇: 编程之美-队列中取最大值操作问题