难度中等,主要考察的是链表的熟练度。
思路:创建一个新的节点,然后遍历两个链表,直到两个链表遍历结束。
需要注意:1.相加到10之后需要进一。
2.边界问题。
public class Solution {
// 测试用例
public static void main(String[] args) {
Solution solution = new Solution();
ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
solution.addTwoNumbers(l1, l2).print();
}
// 具体实现
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(-1);
ListNode node = listNode;
int temp = 0, val1, val2;
while (l1 != null || l2 != null || temp != 0){
val1 = 0; val2 = 0;
if (l1 != null){
val1 = l1.val;
l1 = l1.next;
}
if (l2 != null){
val2 = l2.val;
l2 = l2.next;
}
int value = val1 + val2 + temp;
temp = value / 10;
value = value % 10;
node.next = new ListNode(value);
node = node.next;
}
return listNode.next;
}
}
// 链表节点
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
public void print(){
System.out.print(this.val + " ");
if (this.next != null){
this.next.print();
}
}
}
我觉得不难,哈哈哈,有更好的解决办法可以一起交流一下。