java链表的公共部分_Java找出两个链表的第一个公共节点

题目描述

输入两个链表,找出它们的第一个公共结点。

我的思路:因为是链表,长度都是未知的,不能盲目的两个一起开始自增判断。

首先需要得到 L1的长度 和 L2的长度,让较长的那个先走 (length1-length2)步。然后再一直next去判断。

AC代码, 34ms,503K

/*

public class ListNode {

int val;

ListNode next = null;

ListNode(int val) {

this.val = val;

}

}*/

public class Solution {

public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {

if(pHead1==pHead2){

return pHead1;

}

int l1=getLength(pHead1);

int l2=getLength(pHead2);

if(l1>l2){

for(int i=0;i

pHead1=pHead1.next;

}

}else{

for(int i=0;i

pHead2=pHead2.next;

}

}

boolean f=true;

ListNode p=null;

while(f){

if(pHead1==null||pHead2==null){

return null;

}

if(pHead1==pHead2){

p=pHead1;

f=false;

}else{

pHead1=pHead1.next;

pHead2=pHead2.next;

}

}

return p;

}

public static int getLength(ListNode pHead) {

int length = 0;

ListNode current = pHead;

while (current != null) {

length++;

current = current.next;

}

return length;

}

}

看看别的思路:

1、用HashMap:

第一个while是把pHead1的所有节点都放进去。

第二个while开始,对pHead2的每个节点都用  containsKey 方法来判断。

因为在前一种思路中,要求得两个链表的长度就需要对两个链表进行一次遍历,用HashMap的方法其实更加节省时间。

33ms,503K

import java.util.*;

/*

public class ListNode {

int val;

ListNode next = null;

ListNode(int val) {

this.val = val;

}

}*/

public class Solution {

public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {

ListNode current1 = pHead1;

ListNode current2 = pHead2;

HashMap hashMap = new HashMap();

while (current1 != null) {

hashMap.put(current1, null);

current1 = current1.next;

}

while (current2 != null) {

if (hashMap.containsKey(current2))

return current2;

current2 = current2.next;

}

return null;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值