如题
这次还是用砸门之前自制的“土特产”–链表,来实现加法
话不多说,上node,这里的node很简单,就放个值和指向下一个点的“指针”(go的指针太上头了,现在看啥都像指针:-) )
class Node {
private int val;
public Node next;
public Node(){
}
public Node(int value){
this.val=value;
}
public Node(int value,Node nextnode){
this.val=value;
this.next=nextnode;
}
public String getvalString(){
return String.valueOf(this.val);
}
public Integer getvalInteger(){
return this.val;
}
}
上链表,如果你觉得这个太长,不好记,砸门再把它"解剖"了
public class LinkList{
public Node head;
public LinkList(){}
public LinkList(Node newhead){
this.head=newhead;
}
public static LinkList ToLinkList(String value){
Node head=new Node();
Node node=head;
LinkList list=new LinkList();
for (int i = value.length()-1; i >=0; i--) {
node.next=new Node(value.charAt(i)-'0');
node=node.next;
}
list.head=head;
return list;
}
// return one+two
public static LinkList Sum(LinkList one,LinkList two){
LinkList res=new LinkList();
Node head=new Node();
Node node=head;
res.head=head;
Node onehead=one.head;
Node twohead=two.head;
int b=0;
while(onehead.next!=null||twohead.next!=null){
int originone=0;
int origintwo=0;
if (onehead.next!=null){
originone=onehead.next.getvalInteger();
onehead=onehead.next;
}
if (twohead.next!=null){
origintwo=twohead.next.getvalInteger();
twohead=twohead.next;
}
int resnum=originone+origintwo+b;
System.out.println("this circle res equal to "+resnum);
b=resnum/10;
resnum=resnum%10;
node.next=new Node(resnum);
node=node.next;
}
if (b>0){
node.next=new Node(b);
}
return res;
}
@Override
public String toString(){
StringBuffer sbf=new StringBuffer();
Node node=this.head;
while (node.next!=null){
sbf.append(node.next.getvalInteger());
node=node.next;
}
sbf.reverse();
return sbf.toString();
}
public void output(){
System.out.println(this.toString());
}
}
ToLinkList,就是将string字符串转换为砸门的LinkList。
head是门面,LinkList的门面,node是跑腿的,负责将那些值一个一个放在node里面,就像个外卖小哥,node是送外卖的人,里面的每份Node的实例就是外卖,每份外卖都是独一无二的,但是每份外卖(Node)里面有指向下一份外卖的地址。
并且这里是字符串的尾部先进去,算和时,因为你第一个读到的数就要开始计算了,为了避免再倒回来,所以你第一个必须从个位开始读(你也不想从千百位开始算加法吧,sir :-\ )
public static LinkList ToLinkList(String value){
Node head=new Node();
Node node=head;
LinkList list=new LinkList();
for (int i = value.length()-1; i >=0; i--) {
node.next=new Node(value.charAt(i)-'0');
node=node.next;
}
list.head=head;
return list;
}
上加法,加法有一半都在定义,这里的node,onehead,twohead和上面node一样,都是外卖小哥(“指针”)
// return one+two
public static LinkList Sum(LinkList one,LinkList two){
LinkList res=new LinkList();
Node head=new Node();
Node node=head;
res.head=head;
Node onehead=one.head;
Node twohead=two.head;
int b=0;
while(onehead.next!=null||twohead.next!=null){
int originone=0;
int origintwo=0;
if (onehead.next!=null){
originone=onehead.next.getvalInteger();
onehead=onehead.next;
}
if (twohead.next!=null){
origintwo=twohead.next.getvalInteger();
twohead=twohead.next;
}
int resnum=originone+origintwo+b;
System.out.println("this circle res equal to "+resnum);
b=resnum/10;
resnum=resnum%10;
node.next=new Node(resnum);
node=node.next;
}
if (b>0){
node.next=new Node(b);
}
return res;
}
测试