package zuochengyun.chapter2;
/*
* 链表的加法可用于大数字的相加
*/
public class AddLists {
public static Node addLists(Node head1,Node head2) {
head1=ReverseList.reverseList(head1);
head2=ReverseList.reverseList(head2);
int n1=0;
int n2=0;
int n=0;
int ca=0;
Node node1=head1;
Node node2=head2;
Node node=null;
Node next=null;
while(node1!=null||node2!=null){
n1=node1!=null?node1.value:0;
n2=node2!=null?node2.value:0;
n=n1+n2+ca;
ca=n/10;
n=n%10;
next=node;
node=new Node(n);
node.next=next;
node1=node1!=null?node1.next:null;
node2=node2!=null?node2.next:null;
}
if(ca==1){
next=node;
node=new Node(1);
node.next=next;
}
ReverseList.reverseList(head1);
ReverseList.reverseList(head2);
return node;
}
}
package zuochengyun.chapter2;
public class GetIntersectNode {
//获得某个链表的环的入环点
public static Node getLoopNode(Node head){
if(head==null||head.next==null||head.next.next==null){
return null;
}
Node node1=head.next;
Node node2=head.next.next;
while(node1!=node2){
if(node1.next==null||node2.next==null||node2.next.next==null){//两者中的至少有一个到尽头了都还没有相遇
return null;
}
node1=node1.next;
node2=node2.next.next;
}
node2=head;
while(node1!=node2){
node1=node1.next;
node2=node2.next;
}
return node1;
}
//获得两个无环链表的相加点
public static Node noLoop(Node head1,Node head2){
if(head1==null||head2==null){
return null;
}
Node cur1=head1;
Node cur2=head2;
int n=0;
while(cur1.next!=null){
cur1=cur1.next;
n++;
}
while(cur2.next!=null){
cur2=cur2.next;
n--;
}
if(cur1!=cur2){//在此处已经判断两链表是否有相交节点,无则返回,有则继续往后面求解此节点
return null;
}
cur1=n>0?head1:head2;
cur2=cur1==head1?head2:head1;
n=Math.abs(n);
while(n!=0){
cur1=cur1.next;
n--;
}
while(cur1!=cur2){
cur1=cur1.next;
cur2=cur2.next;
}
return cur1;
}
//求有环的2个链表的相加节点
public static Node bothLoop(Node head1,Node loop1,Node head2,Node loop2){
if(head1==null||head2==null)
return null;
Node n1=head1;
Node n2=head2;
if(loop1==loop2){
return noLoop(n1, n2);
}
else{
Node cur1=loop1.next;
while(cur1!=loop1){
if(cur1==loop2)
return cur1;
cur1=cur1.next;
}
return null;
}
}
public static Node getIntersectNode(Node head1,Node head2) {
if(head1==null||head2==null)
return null;
Node loop1=getLoopNode(head1);
Node loop2=getLoopNode(head2);
if(loop1==null&&loop2==null){
return noLoop(head1, head2);
}
else if(loop1!=null&&loop2!=null){
return bothLoop(head1, loop1, head2, loop2);
}
return null;
}
}