您的位置:首页 > 其它

两个单连生成相加链表

2017-08-07 22:25 225 查看
有两个单链表。代表两个非负数,每个节点代表一个数位。数字是反向存储的。即第一个结点表示最低位。最后一个结点表示最高位。求两个数的相加和,而且以链表形式返回。

import java.util.Stack;

/**
* Created by 糖糖 on 2017/8/7.
*/
public class addList {
public static node addList(node n1,node n2){
Stack<node> s1 = new Stack<>();
Stack<node> s2 = new Stack<>();
while (n1!=null){
s1.add(n1);
n1 = n1.next;
}
while (n2 != null){
s2.add(n2);
n2 = n2.next;
}
int ca = 0;
int p = 0;
int q = 0;
node pre = null;
node cur = null;
int sum = 0;
while (!s1.isEmpty()||!s2.isEmpty()){
p = s1.isEmpty()? 0 :s1.pop().data;
q = s2.isEmpty()?0:s2.pop().data;
sum = p+q+ca;
pre = cur;
cur = new node(sum%10);
ca = sum/10;
cur.next = pre;
}
if(ca==1){
pre = cur;
cur = new node(1);
cur.next = pre;
}
return  cur;
}
/*
先将两个链表翻转,然后直接相加,就省掉了两个栈的空间
*/
public static  node addList2(node head1,node head2){
head1 = reserve(head1);
head2 = reserve(head2);

int ca =0;
int p = 0;
int q =0;
int sum = 0;
node n1 = null;
node n2 = null;
node c1 = head1;
node c2 = head2;
while (c1!=null || c2!=null){
p = c1==null?0:c1.data;
q = c2==null?0:c2.data;
sum = p+q+ca;
n1 = n2;
n2 = new node(sum%10);
n2.next = n1;
ca = sum/10;
c1 = c1==null?null:c1.next;
c2 = c2==null?null:c2.next;
}

if(ca!=0){
n1 = n2;
n2 = new node(1);
n2.next = n1;
}
reserve(head1);
reserve(head2);
return  n2;
}

public  static node reserve(node head){
node pre = null;
node cur = head;
node next = null;
while (cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return  pre;
}

public  static void main(String args[]){
node n1=new node(2);
node n2=new node(5);
node n3=new node(6);
node n4=new node(7);
n1.next=n2;
n2.next=n3;
n3.next=n4;
node n5=new node(2);
node n6=new node(6);
node n7=new node(1);
//n4.next=n5;
n5.next=n6;
n6.next=n7;

//node res = addList(n1,n5);
node res = addList(n1,n5);
while (res != null){
System.out.print(res.data+" ");
res = res.next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: