02.07. 链表相交

复制代码
 1 //暴力法
 2     ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
 3         if (headA == nullptr || headB == nullptr) return nullptr;
 4         ListNode* p, * q;
 5         p = headA;
 6         q = headB;
 7         while (p != nullptr)
 8         {
 9             q = headB;
10             while (q != nullptr)
11             {
12                 if (p == q)
13                     return p;
14                 q = q->next;
15             }
16             p = p->next;
17         }
18         if (p == nullptr || q == nullptr) return nullptr;
19         else return p;
20     };
21     //差值法
22     ListNode* getIntersectionNode1(ListNode* headA, ListNode* headB) {
23         if (headA == nullptr || headB == nullptr) return nullptr;
24         ListNode* curA = headA;
25         ListNode* curB = headB;
26         int lenA = 0, lenB = 0;
27         while (curA != NULL) { // 求链表A的长度
28             lenA++;
29             curA = curA->next;
30         }
31         while (curB != NULL) { // 求链表B的长度
32             lenB++;
33             curB = curB->next;
34         }
35         if (lenB > lenA)
36         {
37             swap(lenB, lenA);
38             swap(curA, curB);
39         }
40         int gap = lenA - lenB;
41         while (gap--)
42         {
43             curA = curA->next;
44         }
45         while (curA != NULL) {
46             if (curA == curB) {
47                 return curA;
48             }
49             curA = curA->next;
50             curB = curB->next;
51         }
52         return NULL;
53     };
复制代码

 

posted @   xiazichengxi  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩