写点什么

第 8 周作业一

用户头像
ruettiger
关注
发布于: 2020 年 07 月 29 日

有两个单向链表(链表长度分别为 m,n),这两个单向链表有可能在某个元素合并,如下图所示的这样,也可能不合并。

现在给定两个链表的头指针,在不修改链表的情况下,如何快速地判断这两个链表是否合并?

如果合并,找到合并的元素,也就是图中的 x 元素。

请用(伪)代码描述算法,并给出时间复杂度和空间复杂度。

/**
* 1.定义单链表
* 2.如果有任意链表为空则不存在交点
* 3.如果链表存在交点可以看到第一个链表和第二个链表交叉拼接则遍历拼接,如果有交点遍历则必在交点处相遇
* 4.对两个链表进行遍历,结束条件是找到交点或者遍历结束
* 时间复杂度为O(m+n),空间复杂度为O(1)
*/
public class CycleLinkList {
public ListNode cycleLinkListNode(ListNode head1, ListNode head2) {
if (head1 == null || head2 == null) return null;
ListNode currentNode1 = head1;
ListNode currentNode2 = head2;
while (currentNode1 != currentNode2) {
currentNode1 = (currentNode1 == null) ? head2 : currentNode1.next;
currentNode2 = (currentNode2 == null) ? head1 : currentNode2.next;
}
return currentNode1;
}
}
class ListNode {
int value;
ListNode next;
public ListNode(int value) {
this.value = value;
this.next = null;
}
}



用户头像

ruettiger

关注

还未添加个人签名 2018.05.30 加入

还未添加个人简介

评论

发布
暂无评论
第8周作业一