输入两个链表,找出它们的第一个公共结点
Posted a1225234
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了输入两个链表,找出它们的第一个公共结点相关的知识,希望对你有一定的参考价值。
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 head = pHead1;
Set<ListNode> res= new HashSet<ListNode>();
while(head!=null)
res.add(head);
head = head.next;
head = pHead2;
while(head!=null)
if(res.contains(head))
break;
head = head.next;
return head;
求出两个链表长度差
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)
int len1=0,len2=0;
ListNode head = pHead1;
while(head!=null)
len1++;
head = head.next;
head = pHead2;
while(head!=null)
len2++;
head = head.next;
ListNode maxList=null,minList=null;
int lenc = Math.abs(len1-len2);
if(len1>=len2)
maxList = pHead1;
minList = pHead2;
if(len2>len1)
maxList = pHead2;
minList = pHead1;
while(lenc!=0)
maxList = maxList.next;
lenc--;
while(maxList!=minList)
maxList = maxList.next;
minList = minList.next;
return maxList;
以上是关于输入两个链表,找出它们的第一个公共结点的主要内容,如果未能解决你的问题,请参考以下文章