Java用链表实现减法,咋判断是上第一个数比第二个数大还是第二个数比第一个数大,我判断过后,链表回不去了>︿<
public Linkedlist sub(){
Linkedlist res=new Linkedlist();Node head=new Node();Node pre=head;int ne=0;
while (this.first.head!=null && this.second.head!=null) {
if (compare()) {
int ae=this.first.head.val-this.second.head.val-ne;
if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}
else{pre.next=new Node(ae);ne=0;}
this.first.head=this.first.head.next;this.second.head=this.second.head.next;pre=pre.next;
}
else{
int ae=-this.first.head.val+this.second.head.val-ne;if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}else{pre.next=new Node(ae);ne=0;}
this.first.head=this.first.head.next;this.second.head=this.second.head.next;pre=pre.next;
}
}
while (this.first.head==null && this.second.head!=null) {
int ae=this.second.head.val-ne;if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}else{pre.next=new Node(ae);ne=0;}
pre=pre.next;this.second.head=this.second.head.next;if (this.second.head==null) {pre.next=new Node('-');break;}
}
while (this.first.head!=null && this.second.head==null) {
int ae=this.first.head.val-ne;if (ae<0) {ae=-ae;pre.next=new Node(ae);ne=1;}else{pre.next=new Node(ae);ne=0;}
pre=pre.next;this.first.head=this.first.head.next;
}
if (ne==1) {pre.next=new Node('-');}
return res;
}
public boolean compare(){
Linkedlist te=this.first;Linkedlist de=this.second;
while (te.head!=null && de.head!=null) {
te.head=te.head.next;de.head=de.head.next;
}
if (te.head == null && de.head!=null) {return true;}
else{return false;}
// if else (this.first.head==null && this.second.head==null) {return false;}
}
这是我的节点结构
class Node{
Node next=null;
int val;
public Node(){}
public Node(int val){
this.val=val;
}
public Node(int val,Node next){
this.val=val;this.next=next;
}
}