题目:输入两个链表,找出他们的第一个公共结点。
分析:
方法1:直接采用遍历的方法,从第一个链表的第一个元素开始分别与第二个链表的所有元素比较,直到相等为止,相等即找到了公共结点。
方法2:先分别遍历两个链表,分别得到链表的长度n,m,然后对长的链表进行遍历,遍历的节点数为|n-m|,最后再依次按顺序遍历两个链表并比较结点是否相等。
代码如下:
package problem2;
/**
* @author Hutongling
*
* @time:2017年3月29日 上午10:57:21
*/
public class 两个链表的第一个公共结点 {
//方法1:使用蛮力方法,直接从头开始比较
static Node findTheFirstSameNode(Node list1,Node list2){
if(list1==null || list2==null)
return null;
else{
Node head1=list1;
Node head2=list2;
while(head1!=null){
while(head2!=null){
if(head1.value!=head2.value)
head2=head2.next;
else {
return head1;
}
}
head1=head1.next;
head2=list2;
}
return head1;
}
}
//第二种方法:先遍历两个链表,得到两个链表的长度,然后从长的链表开始遍历到两个链表长度差的位置,接着开始对两个链表同时开始遍历
static Node findTheSameNode1(Node list1,Node list2){
if(list1 ==null || list2==null)
return null;
else{
Node head1=list1;
Node head2=list2;
int count1=0,count2=0;
while(head1!=null){
count1++;
head1=head1.next;
}
while(head2!=null){
count2++;
head2=head2.next;
}
System.out.println("表1的长度为:"+count1 + "\n表2的长度为: " + count2);
head1=list1;
head2=list2;
int tempCount=0;
if(count1>count2){
for(int i=1;i<=count1-count2;i++)
head1=head1.next;
while(head1!=null && head2!=null){
if(head1.getValue()==head2.getValue())
return head1;
else{
head1=head1.next;
head2=head2.next;
}
}
}else {
while(head2!=null){
tempCount++;
if(tempCount<count1-count2)
head2=head2.next;
else break;
}
while(head1!=null && head2!=null){
if(head1.getValue()==head2.getValue())
return head1;
else{
head1=head1.next;
head2=head2.next;
}
}
}
return null;
}
}
public static void main(String[] args) {
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(6);
Node node5=new Node(7);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
Node nodeS1=new Node(4);
Node nodeS2=new Node(5);
Node nodeS3=new Node(6);
Node nodeS4=new Node(7);
nodeS1.next=nodeS2;
nodeS2.next=nodeS3;
nodeS3.next=nodeS4;
Node sameNode=findTheFirstSameNode(node1,nodeS1);
System.out.println(sameNode.getValue());
Node sameNode1=findTheSameNode1(node1,nodeS1);
System.out.println(sameNode1.getValue());
}
}
代码结果:
6
表1的长度为:5
表2的长度为: 4
6