# java-7.微软亚院之编程判断俩个链表是否相交 给出俩个单向链表的头指针，比如 h1 ， h2 ，判断这俩个链表是否相交

```

/**
* we deal with two main missions:
*
* A.
* 1.we create two joined-List(both have no loop)
* 2.whether list1 and list2 join
* 3.print the joinPoint
*
* B.
* 1.create loop in list1 by itself
* 2.whether the list has loop
* 3.print the firstNode of loop
*/
public static void main(String[] args) {
int[] a={1,2,3,4,5,6,7,8,9,10};
System.out.print("List1=");
list1.display();

int[] b={11,12};
ListNode joinPoint=list1.getNodeAt(3);
ListNode tail02=list2.getTail();
tail02.next=joinPoint;
//now list2=11->12->3->4->5 ->6->7->8->9-> 10
System.out.print("List2=");
list2.display();

//create a loop to find the join-point
tail02=list2.getTail();
System.out.println("The two joinedLink's joinPoint is "+firsrNodeInLoop.data);

//delete the loop
tail02.next=null;

list1.setLoop(5);//create a loop like following:
/*now list1=
________________
/			       |
1->2->3->4->5 ->6->7->8->9-> 10

*/
if(meetingPoint!=null){
System.out.println("Now List1  hasLoop,lowPoint&&fastPoint meets at  "+meetingPoint.data);
System.out.println("firstNode of Loop is "+firsrNodeInLoop.data);
}

}

//whether list1 and list2 join
}
}
System.out.println("joined");
}else{
System.out.println("not joined");
}
}
}

//建立单链表有两种方法：头插法建表和尾插法，后者需多建立一个尾指针
//这里我用头插法
public ListNode create(int[] a){
ListNode firstNode=null;
//starts with the last element
for(int i=a.length-1;i>=0;i--){
ListNode node=new ListNode(a[i]);
node.next=firstNode;
firstNode=node;
}
return firstNode;
}

//if hasLoop,return the "Meeting-point".
while(p2!=null&&p2.next!=null){
p1=p1.next;
p2=p2.next.next;
if(p1==p2){
return p1;
}
}
return null;
}

//display LinkList's elements while it has no loop
public void display(){
while(p!=null){
System.out.print(p.data+",");
p=p.next;
}
System.out.println();
}

//get the a[position]
public ListNode getNodeAt(int position){
while(--position>0){
node=node.next;
}
return node;
}

//create a loop. Make tail's nextElement is a[i]
public void setLoop(int i){
while(p!=null&&p.next!=null){
p=p.next;
}
ListNode loopPoint=getNodeAt(i);
p.next=loopPoint;
}

//p1 traverse from head while p2 from "Meeting-point".When they meets,it's the firstNode of loop
ListNode re=null;
if(p2!=null){
while(true){
p2=p2.next;
p1=p1.next;
if(p1==p2){
re=p1;
break;
}
}
}
return re;
}

//get the last node of LinkList
public ListNode getTail(){
while(p.next!=null){
p=p.next;
}
return p;
}

}
public void clear(){
}

}

class ListNode{
int data;
ListNode next;
public ListNode(int data){
this.data=data;
}
}

```

java-7.微软亚院之编程判断俩个链表是否相交 给出俩个单向链表的头指针，比如 h1 ， h2 ，判断这俩个链表是否相交

• 0

开心

• 0

板砖

• 0

感动

• 0

有用

• 0

疑问

• 0

难过

• 0

无聊

• 0

震惊

先看看原题：《编程之美》3.6编程判断两个链表是否相交，原题假设两个链表不带环。 　　为了防
先看看原题：《编程之美》3.6编程判断两个链表是否相交，原题假设两个链表不带环。 注：位于(*)