Skip to main content

Add Two Linked Lists

题目 NOTE

  1. 要点不要忘了最后的进位
  2. 两个单链表可以长度任意
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);
StringBuilder sb = new StringBuilder();
while (result != null) {
sb.append(result.val);
result = result.next;
}
System.out.println("sb = " + sb);

}

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;
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;
}
}
Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
  • Attribution: Retain the original author's signature and code source information in the original and derivative code.
  • Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
The documentation part of this work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License . You may freely share, including copying and distributing this work in any medium or format, and freely adapt, remix, transform, and build upon the material. However, you are required to:
  • Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
  • NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
  • ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.