您的位置:首页 > 其它

两个链表的第一个公共结点(链表)

2017-11-21 14:42 113 查看
题目描述:输入两个链表,找出它们的第一个公共结点。

public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}

思路一:
找出2个链表的长度,然后让长的先走两个链表的长度差,然后再一起走 (因为2个链表用公共的尾部)。

public class Solution {
public static void main(String[] args) {
ListNode p1 = new ListNode(6);
ListNode p2 = new ListNode(7);
p1.next = p2;
ListNode pp1 = new ListNode(1);
pp1.next = p1;
Solution s = new Solution();
System.out.println(s.FindFirstCommonNode(p1,pp1).val);
}
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) return null;
int len1 = ListLen(pHead1);
int len2 = ListLen(pHead2);
if (len1 >= len2)
pHead1 = walkStep(pHead1, len1 - len2);
else if (len1 < len2)
pHead2 = walkStep(pHead2, len2 - len1);
while (pHead1 != null)
{
if (pHead1 == pHead2) return pHead1;
else {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
}
return null;
}
private int ListLen(ListNode pHead)
{
int len = 0;
ListNode current = pHead;
while (current != null)
{
len++;
current = current.next;
}
return len;
}
private ListNode walkStep(ListNode pHead, int step)
{
while (step > 0)
{
pHead = pHead.next;
step--;
}
return pHead;
}
}

思路二:
假定:List1长度: a+n,List2长度:b+n, 且 a<b         

那么,p1会先到链表尾部,这时p2走到a+n位置,将p1换成List2头部。         

接着,p2 再走b+n-(n+a) =b-a步到链表尾部,这时p1也走到List2的b-a位置,还差a步就到可能的第一个公共节点。         

将p2换成 List1头部,p2走a步也到可能的第一个公共节点。

如果恰好p1==p2,那么p1就是第一个公共节点。 

或者p1和p2一起走n步到达列表尾部,二者没有公共节点,退出循环。 

同理a>=b。

时间复杂度O(n+a+b)

public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) return null;
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while (p1 != p2)
{
p1 = (p1 == null)? pHead2 : p1.next;
p2 = (p2 == null) ? pHead1 : p2.next;
}
return p1;
}
}

思路三:利用HashMap

import java.util.HashMap;
import java.util.Map;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) return null;
Map<ListNode, Integer> map = new HashMap<>();
while (pHead1 != null)
{
map.put(pHead1, null);
pHead1 = pHead1.next;
}
while (pHead2 != null)
{
if (map.containsKey(pHead2)) return pHead2;
else pHead2 = pHead2.next;
}
return pHead2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: