请教一个单链表算法

K行天下 2008-09-17 04:44:48
在C++版看的一个面试题

Assume you have two singly linked lists, denoted as L1 and L2. It is possible that L1 and L2
meet on some node and have a common tail. If L1 has m nodes and L2 has n nodes, then what is
the best time complexity to check if the two linked lists meet and to find out the meeting point?
(Only O(1) constant amont of extra storage space is allowed.)

A. O((m+n)*log(m+n))

B. O(m*n)

C. O(m+n)

D. O((m+n)*log(m*n))

E. O(log(m*n))


请问各位算法大牛的算法,想不出O(m+n)的
...全文
66 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
oo 2008-09-17
  • 打赏
  • 举报
回复
遍历L1和L2,记录L1和L2的长度length1和length2,同时记录最后一个node,node1和node2
如果node1和node2是相同的,则有交叉,否则没有。
如果有交叉,length1和length2中长的那个list先移动|length1-length2|的距离,然后一一比较,找到第一个相同的node则为交叉点。
  • 打赏
  • 举报
回复
设交叉节点在L1链表中是第i个节点、在L2链表中是第j个节点,那么必定有:
i-j=m-n
利用这个性质就可以在O(m+n)时间内解决问题。

33,006

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧