原题:
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解题:
自定义了一个简单链表结构:
public class LinkList {
public LinkNode head;
public LinkList(){
head = new LinkNode(null);
}
public void addNode(LinkNode addNode){
head.addNode(addNode);
}
public void print(){
LinkNode node = head.next;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("HEAD-->");
while (node!= null) {
stringBuilder.append(node.data+"-->");
node = node.next;
}
System.out.println(stringBuilder.toString());
}
}
class LinkNode{
Integer data;
LinkNode next;
public LinkNode(Integer data){
this.data = data;
}
protected void addNode(LinkNode node){
if(this.next == null){
this.next = node;
}else{
this.next.addNode(node);
}
}
protected void insertNode(LinkNode node){
if(this.next == null){
this.next = node;
} else {
LinkNode temp = this.next ;
this.next = node;
node.next =temp;
}
}
}
根据链表解题方法如下:
private static LinkList sumLinkTwo(LinkList linkOne,LinkList linkTwo){
LinkList result = new LinkList();
LinkNode one = linkOne.head.next;
LinkNode two = linkTwo.head.next;
boolean isSuperBit = false;
while (one != null && two != null) {
int sumBit = one.data + two.data;
sumBit += isSuperBit ? 1 : 0;
if(sumBit >= 10){
sumBit = sumBit % 10;
isSuperBit = true;
} else {
isSuperBit = false;
}
result.addNode(new LinkNode(sumBit));
one = one.next;
two = two.next;
}
while (one != null){
int sumBit = one.data;
sumBit += isSuperBit ? 1 : 0;
if(sumBit >= 10){
sumBit = sumBit % 10;
isSuperBit = true;
} else {
isSuperBit = false;
}
result.addNode(new LinkNode(sumBit));
one = one.next;
}
while (two != null){
int sumBit = two.data;
sumBit += isSuperBit ? 1 : 0;
if(sumBit >= 10){
sumBit = sumBit % 10;
isSuperBit = true;
} else {
isSuperBit = false;
}
result.addNode(new LinkNode(sumBit));
two = two.next;
}
//遍历完成两个链表之后 要判断是否有溢出位
if(isSuperBit ){
result.addNode(new LinkNode(1));
}
return result;
}