标签:null sum return 链表 linked res ati || targe
package whale.leetcode.simple;
/**
* @Author: WhaleFall541
* @Date: 2021/5/29 20:30
*/
public class AddTwoSumLinkedList {
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/*
[9,9,9,9,9,9,9]
[9,9,9,9]
*/
public static void main(String[] args) {
ListNode l1 = new ListNode(9, new ListNode(9, new ListNode(9,
new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
ListNode l2 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));
ListNode result = addTwoNumbers(l1, l2);
while (result != null) {
System.out.println(result.val);
result = result.next;
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result;
ListNode head = result = new ListNode();
int temp=0, value1, value2;
while (l1 != null || l2 != null) {
value1 = (l1 == null) ? 0 : l1.val;
value2 = (l2 == null) ? 0 : l2.val;
// 当前指针位值的值相加
result.val = value1 + value2 + temp;
// 进位每次加完就置为0
temp = 0;
if (result.val > 9) {
temp = result.val / 10;// 记录进位的值
result.val = result.val % 10;// 记录当前位的值
}
// l1 l2 只要不为空则后移指针
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
// l1 l2 只要其一不为空则结果集需要后延一位
if (l1 != null || l2 != null)
result = result.next = new ListNode();
}
if (temp!=0)
result.next = new ListNode(temp);
return head;
}
}
标签:null sum return 链表 linked res ati || targe
原文地址:https://www.cnblogs.com/whalefall541/p/14826519.html