博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode. Intersection of Two Linked Lists
阅读量:5157 次
发布时间:2019-06-13

本文共 1809 字,大约阅读时间需要 6 分钟。

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.

只需要将listB首位相连,这样listA和listB就形成了一个带有环的链表。

这样题目就变成了

1 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)  2     { 3         ListNode *tail, *join; 4         if (headA == NULL || headB == NULL) 5             return NULL; 6              7         for (tail = headB; tail->next != NULL; tail = tail->next); // reach tail 8         tail->next = headB; // create a circle 9         join = detectCycle(headA);10         tail->next = NULL; // keep list B as original11         12         return join;13     }14     15     ListNode *detectCycle(ListNode *head)16     {17         ListNode *fast = head, *slow = head;18         19         while (fast != NULL)20         {21             slow = slow->next;22             fast = fast->next;23             if (fast != NULL)24                 fast = fast->next;25             if (fast != NULL && fast == slow) // catch slow26                 break;27         }28         29         if (fast == NULL)30             return NULL;31             32         slow = head;33         while (slow != fast)34         {35             slow = slow->next;36             fast = fast->next;37         }38         return slow;39     }

 

转载于:https://www.cnblogs.com/ym65536/p/4141555.html

你可能感兴趣的文章
201421410014蒋佳奇
查看>>
Xcode5和ObjC新特性
查看>>
Centos 7.0 安装Mono 3.4 和 Jexus 5.6
查看>>
CSS属性值currentColor
查看>>
Real-Time Rendering 笔记
查看>>
多路复用
查看>>
spring IOC装配Bean(注解方式)
查看>>
处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“Manag
查看>>
利用SignalR来同步更新Winfrom
查看>>
反射机制
查看>>
CocoaPod
查看>>
BZOJ 1251: 序列终结者 [splay]
查看>>
5G边缘网络虚拟化的利器:vCPE和SD-WAN
查看>>
MATLAB基础入门笔记
查看>>
【UVA】434-Matty's Blocks
查看>>
Android开发技术周报 Issue#80
查看>>
hadoop2.2.0+hive-0.10.0完全分布式安装方法
查看>>
django知识点总结
查看>>
C++ STL stack、queue和vector的使用
查看>>
使用Reporting Services时遇到的小问题
查看>>