package com.linkedList;
编程判断俩个链表是否相交 给出俩个单向链表的头指针,比如 h1 , h2 ,判断这俩个链表是否相交
public class LinkListTest01 {
public static void main(String[] args) {
MyLinkList list1 = new MyLinkList();
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ListNode head1 = list1.create(a);
System.out.print("List1=");
list1.display();
MyLinkList list2 = new MyLinkList();
int[] b = { 11, 12 };
ListNode head2 = list2.create(b);
ListNode joinPoint = list1.getNodeAt(3);
ListNode tail02 = list2.getTail();
tail02.next = joinPoint;
System.out.print("List2=");
list2.display();
isJoined(head1,head2);
tail02 = list2.getTail();
tail02.next= head2;
ListNode firstNodeInLoop = list1.getFirstNodeInLoop(head1);
System.out.println("The two joinedLink's joinPoint is "+firstNodeInLoop.data);
tail02.next = null;
list1.setLoop(5);
ListNode meetingPoint = list1.hasLoop(head1);
if(meetingPoint!=null){
System.out.println("Now List1 hasLoop,lowPoint&&fastPoint meets at "+meetingPoint.data);
firstNodeInLoop=list1.getFirstNodeInLoop(head1);
System.out.println("firstNode of Loop is "+firstNodeInLoop.data);
}
}
public static void isJoined(ListNode head1, ListNode head2) {
while (head1.next != null) {
head1 = head1.next;
}
while (head2.next != null) {
head2 = head2.next;
}
if (head1 == head2) {
System.out.println("joined");
} else {
System.out.println("not joined");
}
}
}
class MyLinkList {
private ListNode head;
public ListNode create(int[] b) {
ListNode firstNode = null;
for (int i = b.length - 1; i >= 0; i--) {
ListNode node = new ListNode(b[i]);
node.next = firstNode;
firstNode = node;
}
head = firstNode;
return firstNode;
}
public ListNode hasLoop(ListNode head) {
ListNode p1 = head;
ListNode p2 = head;
while (p1 != null && p2 != null) {
p1 = p1.next;
p2 = p2.next.next;
if (p1 == p2) {
return p1;
}
}
return null;
}
public void display() {
ListNode p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
public ListNode getNodeAt(int n) {
ListNode node = head;
while (--n > 0) {
node = node.next;
}
return node;
}
public void setLoop(int i) {
ListNode p = head;
while (p != null && p.next != null) {
p = p.next;
}
ListNode loopPoint = getNodeAt(i);
p.next = loopPoint;
}
public ListNode getFirstNodeInLoop(ListNode head) {
ListNode p1 = head;
ListNode p2 = hasLoop(head);
ListNode re = null;
if (p2 != null) {
while (true) {
p2 = p2.next;
p1 = p1.next;
if (p1 == p2) {
re = p1;
break;
}
}
}
return re;
}
public ListNode getTail() {
ListNode p = head;
while (p.next != null) {
p = p.next;
}
return p;
}
public ListNode getHead() {
return head;
}
public void clear() {
head = null;
}
}
class ListNode {
int data;
ListNode next;
public ListNode(int data) {
this.data = data;
}
}