题目
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例1:
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]
分析
可以先翻转链表,把最低位放到最前面然后开始进行相加,注意和超过10需要进位
java
public class LinkNode {
int val;
LinkNode next;
public LinkNode(int data) {
this.val = data;
this.next = null;
}
}
public class LinkList {
LinkNode head;
public LinkList() {
this.head = null;
}
public LinkNode getHead() {
return this.head;
}
//添加元素
public void addNode(int data) {
LinkNode node = new LinkNode(data);
if (this.head == null) {
this.head = node;
} else {
LinkNode cur = this.head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
//正序打印
public void print(LinkNode node) {
while(node != null) {
System.out.print(node.val);
System.out.print(" ");
node = node.next;
}
System.out.println();
}
public LinkNode addTwoNumbers(LinkNode l1, LinkNode l2) {
LinkNode p1 = reverse(l1);
LinkNode p2 = reverse(l2);
int count = 0;
LinkNode head = new LinkNode(-1);
LinkNode p = head;
while(p1 != null || p2 != null) {
int numa = 0;
if(p1 != null) {
numa = p1.val;
}
int numb = 0;
if(p2 != null) {
numb = p2.val;
}
int sum = numa + numb + count;
if(sum >= 10) {
p.next = new LinkNode(sum % 10);
count = sum / 10;
} else {
p.next = new LinkNode(sum);
count = 0;
}
p = p.next;
if(p1 != null) {
p1 = p1.next;
}
if(p2 != null) {
p2 = p2.next;
}
}
if(count > 0) {
p.next = new LinkNode(count);
p = p.next;
}
LinkNode node = reverse(head.next);
print(node);
return node;
}
public LinkNode reverse(LinkNode l1) {
LinkNode pre = null;
while(l1 != null) {
LinkNode next = l1.next;
l1.next = pre;
pre = l1;
l1 = next;
}
return pre;
}
}
public class addTwoNumbersII {
public static void main(String[] args) {
LinkList list = new LinkList();
list.addNode(7);
list.addNode(2);
list.addNode(4);
list.addNode(3);
LinkList lista = new LinkList();
lista.addNode(5);
lista.addNode(6);
lista.addNode(4);
list.addTwoNumbers(list.getHead(),lista.getHead());
}
}