1.兩個非空鏈表,分別倒敘保存數字,兩個鏈表相加而且返回一個鏈表
//2ms 45.5m
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
LinkedList<Integer> linkedList1 = new LinkedList<Integer>();
LinkedList<Integer> linkedList2 = new LinkedList<Integer>();
while (l1 != null || l2 != null) {
linkedList1.add(0, l1 == null ? 0 : l1.val);
l1 = l1 != null ? l1.next : null;
linkedList2.add(0, l2 == null ? 0 : l2.val);
l2 = l2 != null ? l2.next : null;
}
return getListNode(linkedList1, linkedList2, false);
}
private ListNode getListNode(LinkedList<Integer> ll1, LinkedList<Integer> ll2, boolean isAdd1) {
int num1 = ll1.getLast();
int num2 = ll2.getLast();
int left = num1 + num2 + (isAdd1 ? 1 : 0);
if (left >= 10) {
isAdd1 = true;
left = left % 10;
} else {
isAdd1 = false;
}
ListNode listNode = new ListNode(left);
ll1.removeLast();
ll2.removeLast();
if (!ll1.isEmpty() && !ll2.isEmpty()) {
listNode.next = getListNode(ll1, ll2, isAdd1);
} else if (isAdd1) {
listNode.next = new ListNode(1);
}
return listNode;
}
//2 ms 46 MB
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
複製代碼