Leetcode 2. Add Two Numbers (java)

来源:互联网 时间:2018-03-03

解法:

class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode l3 = null; boolean add = false; while (l1 != null || l2 != null) { //位数相加 int plus; if (l1 == null) { plus = l2.val; } else if (l2 == null) { plus = l1.val; } else { plus = l1.val + l2.val; } if (add) { plus++; add = false; } //生成节点 ListNode temp; if (plus >= 10) { temp = new ListNode(plus % 10); add = true; } else { temp = new ListNode(plus); } //拼接节点 ListNode l3Head = l3; if (l3 == null) { l3 = temp; if (add && (l1 == null || l1.next == null) && (l2 == null || l2.next == null)) { l3.next = new ListNode(1); } } else { while (l3Head.next != null) { l3Head = l3Head.next; } l3Head.next = temp; if (add && (l1 == null || l1.next == null) && (l2 == null || l2.next == null)) { l3Head.next.next = new ListNode(1); } } //跳到下一位 if (l1 == null) { l2 = l2.next; } else if (l2 == null) { l1 = l1.next; } else { l1 = l1.next; l2 = l2.next; } } return l3; }}

最开始有三种思路:

  1. 转换成数值相加后,在转换成链表,但数值过大,使用long也不足以存储
  2. 翻转链表进行相加,但未翻转前更便于相加进位
  3. 直接使用链表进行相加进位

最后采用了最后一种思路

github地址:https://github.com/CyanChan/Leetcode-Record

相关阅读:
Top