Definition for singly-linked list
比方说有链表1:n1 n2 n3 n4
有链表2:n5 n3 n4
实际上n3和n4是同一个,也就是他们在n3时交叉的
如果是分别遍历,复杂度是O(n2),接下来介绍O(n)解法
假设长的链表为len1,短的为len2
那么把长的移动len1-len2
然后两个链表指针可以同时移动了,找到交叉的节点就返回,复杂度O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include <iostream> using namespace std;
struct Node{ int val; Node* next; };
int getLen(Node *p){ int len = 0; while(p != NULL){ len++; p = p->next; } return len; }
Node* listMove(Node*p, int diff){ for(int i = 0; i < diff; i++){ p = p->next; } return p; }
Node* findCommon(Node *l1, Node *l2){ int len1 = getLen(l1); int len2 = getLen(l2); Node *longListP, *shortListP;
if(len1 > len2){ longListP = l1; shortListP = l2; } else{ longListP = l2; shortListP = l1; }
int diff = abs(len1 - len2); longListP = listMove(longListP, diff);
while(longListP != NULL){ if(longListP == shortListP){ return longListP; } longListP = longListP->next; shortListP = shortListP->next; } return NULL; }
int main() { Node n1, n2, n3, n4, n5; Node *l1 = &n1, *l2 = &n5; n1.val = 1; n2.val = 2; n3.val = 3; n4.val = 4; n5.val = 5; n1.next = &n2; n2.next = &n3; n3.next = &n4; n5.next = &n3;
cout << findCommon(l1, l2)->val << endl; }
|