随笔- 509  文章- 0  评论- 151  阅读- 22万 

Intersection of Two Linked Lists

2015.1.23 12:53

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
begin to intersect at node c1.

Notes:

  If the two linked lists have no intersection at all, return null.

  The linked lists must retain their original structure after the function returns.

  You may assume there are no cycles anywhere in the entire linked structure.

  Your code should preferably run in O(n) time and use only O(1) memory.

Solution:

  The problem description especially required the code to run in O(n) time and O(1) space. Thus I came up with the most direct way.

  Just count the lengths of both lists, set two pointers from the list heads, align them to equipotential position and move'em forward until they coincide.

  That would be the answer we seek.

  Time complexity should be O(n + m), if you name the lengths of both lists to be "n" and "m". Extra space required is O(1).

Accepted code:

复制代码
 1 // 1AC, count the number of nodes and align them
 2 /**
 3  * Definition for singly-linked list.
 4  * struct ListNode {
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int x) : val(x), next(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
13         ListNode *p1, *p2;
14         int n1, n2;
15         
16         p1 = headA;
17         n1 = 0;
18         while (p1 != nullptr) {
19             ++n1;
20             p1 = p1->next;
21         }
22         
23         p2 = headB;
24         n2 = 0;
25         while (p2 != nullptr) {
26             ++n2;
27             p2 = p2->next;
28         }
29         
30         p1 = headA;
31         p2 = headB;
32         
33         int i;
34         if (n1 < n2) {
35             for (i = 0; i < n2 - n1; ++i) {
36                 p2 = p2->next;
37             }
38         } else if (n1 > n2) {
39             for (i = 0; i < n1 - n2; ++i) {
40                 p1 = p1->next;
41             }
42         }
43         
44         while (p1 != nullptr && p2 != nullptr && p1 != p2) {
45             p1 = p1->next;
46             p2 = p2->next;
47         }
48         
49         return p1;
50     }
51 };
复制代码

 

 posted on   zhuli19901106  阅读(322)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示