架构师第一期作业(第 8 周)

用户头像
Cheer
关注
发布于: 2020 年 11 月 16 日

有两个单向链表(链表长度分别为 m,n),这两个单向链表有可能在某个元素合并,也可能不合并,如下图所示的这样。现在给定两个链表的头指针,在不修改链表的情况下,如何快速地判断这两个链表是否合并?如果合并,找到合并的元素,也就是图中的 x 元素。请用代码(或伪代码)描述算法,并给出时间复杂度。



算法如下:

# 单向链表节点定义
class Node
attr_accessor :data, :next
def initialize(data, next_node = nil)
@data = data
@next = next_node
end
end
# 模拟堆栈结构
class Stack
def initialize
@array = []
end
def length
@array.length
end
def push item
@array << item
end
def pop
@array.shift
end
end
def find_merge_node head1, head2
stack1 = Stack.new
stack2 = Stack.new
while head1 != null
stack1.push head1
head1 = head1.next
end
while head2 != null
stack2.push head2
head2 = head2.next
end
result = nil
while stack1.length > 0 && stack2.length > 0
node1 = stack1.pop
node2 = stack2.pop
break if node1.data != node2.data
result = node1
end
result
end



时间复杂度为O(m+n),空间复杂度为O(m+n)



发布于: 2020 年 11 月 16 日阅读数: 21
用户头像

Cheer

关注

还未添加个人签名 2018.11.25 加入

还未添加个人简介

评论

发布
暂无评论
架构师第一期作业(第8周)