445. Add Two Numbers II | 链表的整数相加

来源:互联网 发布:川大网络教育入学考试 编辑:程序博客网 时间:2024/06/04 18:17
  • Total Accepted: 15900
  • Total Submissions: 34368
  • Difficulty: Medium
  • Contributors: Admin

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7

Subscribe to see which companies asked this question.


思路:先计算两个链表的长度,将长度大的链表的多余部分头插法,插入到新的链表中去,再同时编辑两个链表,将和设为新节点的值同样头插法插入到新的链表中去,再逆置新的链表,同时修改新链表节点的值,将大于10的取余作为进位,最后返回头结点即可。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode res = new ListNode(-1);res.next = null;ListNode p1 = l1, p2 = l2;int len1 = 0, len2 = 0;while (p1 != null) {len1++;p1 = p1.next;}while (p2 != null) {len2++;p2 = p2.next;}ListNode longNode = p1 = len1 > len2 ? l1 : l2;p2 = (len1 <= len2) ? l1 : l2;int dif = Math.abs(len1 - len2);while (dif > 0) {ListNode node = new ListNode(p1.val);node.next = res.next;res.next = node;p1 = p1.next;dif--;}len1 = len1 < len2 ? len1 : len2;while (p1 != null && p2 != null) {ListNode node = new ListNode(p1.val + p2.val);node.next = res.next;res.next = node;p1 = p1.next;p2 = p2.next;}int jinwei = 0, val;ListNode p = res.next, t;res.next = null;while (p != null) {t = p.next;val = (p.val + jinwei) % 10;jinwei = (p.val + jinwei) / 10;p.val = val;p.next = res.next;res.next = p;p = t;}res.val = jinwei;return jinwei > 0 ? res : res.next;}


0 0